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]) {
|
for (const page of [sender, receiver]) {
|
||||||
await expect(page.locator('#log')).toContainText('waiting for the security check');
|
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
|
// 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(receiver.locator('#incoming')).toContainText(source.split('/').pop()!);
|
||||||
await expect(sender.locator('#log')).toContainText('waiting for the receiver to download');
|
await expect(sender.locator('#log')).toContainText('waiting for the receiver to download');
|
||||||
await expect(receiver.locator('#log')).not.toContainText('receiving');
|
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');
|
await receiver.click('#download');
|
||||||
return started;
|
return started;
|
||||||
}
|
}
|
||||||
@@ -385,6 +389,8 @@ async function transfer(
|
|||||||
}
|
}
|
||||||
await expect(sender.locator('#send-progress')).toHaveJSProperty('value', 100);
|
await expect(sender.locator('#send-progress')).toHaveJSProperty('value', 100);
|
||||||
await expect(receiver.locator('#receive-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.
|
// Removed hidden pages release the service worker for updates.
|
||||||
await expect(receiver.locator('iframe')).toHaveCount(0);
|
await expect(receiver.locator('iframe')).toHaveCount(0);
|
||||||
await expectClosed(sender);
|
await expectClosed(sender);
|
||||||
@@ -633,6 +639,7 @@ for (const name of Object.keys(BROWSERS)) {
|
|||||||
// A transfer that already finished would report no failure.
|
// A transfer that already finished would report no failure.
|
||||||
expect(await download.failure()).toBe('canceled');
|
expect(await download.failure()).toBe('canceled');
|
||||||
await expect(receiver.locator('#log')).toContainText('download cancelled');
|
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);
|
await expect(receiver.locator('iframe')).toHaveCount(0);
|
||||||
expect(await log(receiver)).not.toContain('download complete');
|
expect(await log(receiver)).not.toContain('download complete');
|
||||||
// The window keeps the sender from having sent everything before it hears about the cancel.
|
// 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 withLogs(sender, receiver, async () => {
|
||||||
await start('offline', sender, receiver, source);
|
await start('offline', sender, receiver, source);
|
||||||
await expect(sender.locator('#log')).toContainText('delivered');
|
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) };
|
const other = { name: 'other.bin', mimeType: 'application/octet-stream', buffer: Buffer.alloc(200_000) };
|
||||||
await sender.setInputFiles('input[type=file]', other);
|
await sender.setInputFiles('input[type=file]', other);
|
||||||
await expect(sender.locator('#send-progress')).toHaveJSProperty('value', 100);
|
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.
|
// 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 () => {
|
test(`session: ${name} a new operation ends the previous one`, async () => {
|
||||||
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
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.fill('#receive-code', 'nobody');
|
||||||
await receiver.click('#receive');
|
await receiver.click('#receive');
|
||||||
await expect.poll(() => sockets.get(receiver)!.length).toBeGreaterThan(0);
|
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.
|
// Closes all of the above, transfer checks that.
|
||||||
await transfer('offline', sender, receiver, source, 100_000);
|
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]}`);
|
await expect(receiver.locator('#log')).toContainText(`looking on ${urls[2]}`);
|
||||||
expect([trackers.sockets.length, trackers.open]).toEqual([3, 3]);
|
expect([trackers.sockets.length, trackers.open]).toEqual([3, 3]);
|
||||||
await expect(receiver.locator('#receive-error')).toHaveCount(0);
|
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(
|
await expect(receiver.locator('#log')).toContainText(
|
||||||
`sender via ${tracker} did not connect: this side ${NO_PUBLIC}`,
|
`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.
|
// Then once more for the turn a new offer may have taken meanwhile.
|
||||||
await fastForward('06:00');
|
await fastForward('06:00');
|
||||||
await fastForward(CONNECT_TIMEOUT);
|
await fastForward(CONNECT_TIMEOUT);
|
||||||
|
|||||||
+83
-26
@@ -9,6 +9,7 @@ import {
|
|||||||
DEFAULT_TRACKERS,
|
DEFAULT_TRACKERS,
|
||||||
type Events,
|
type Events,
|
||||||
type Incoming,
|
type Incoming,
|
||||||
|
type Phase,
|
||||||
type ReceiveEvents,
|
type ReceiveEvents,
|
||||||
receiveViaTracker,
|
receiveViaTracker,
|
||||||
sendViaTracker,
|
sendViaTracker,
|
||||||
@@ -83,6 +84,8 @@ function onResetServers() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const file = ref<File>();
|
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 offer = ref('');
|
||||||
const answerInput = ref('');
|
const answerInput = ref('');
|
||||||
const sendCode = ref('');
|
const sendCode = ref('');
|
||||||
@@ -100,6 +103,9 @@ const confirmed = ref(false);
|
|||||||
const log = ref<string[]>([]);
|
const log = ref<string[]>([]);
|
||||||
// Of the session, shown in the card of its side.
|
// Of the session, shown in the card of its side.
|
||||||
const error = ref('');
|
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.
|
// Shared by both sides, each adds its own progress.
|
||||||
const events: Omit<Events, 'progress'> = {
|
const events: Omit<Events, 'progress'> = {
|
||||||
@@ -108,6 +114,7 @@ const events: Omit<Events, 'progress'> = {
|
|||||||
events.log(message);
|
events.log(message);
|
||||||
error.value = message;
|
error.value = message;
|
||||||
},
|
},
|
||||||
|
status: (phase, text) => (status.value = { phase, text }),
|
||||||
check: (result) => {
|
check: (result) => {
|
||||||
check.value = result;
|
check.value = result;
|
||||||
confirmed.value = false;
|
confirmed.value = false;
|
||||||
@@ -134,24 +141,43 @@ const receiveEvents: ReceiveEvents = {
|
|||||||
|
|
||||||
const percent = ({ read, size }: Progress) => (size ? Math.floor((read / size) * 100) : 100);
|
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() {
|
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.
|
// The text copied last and whether that worked. Its button says so, after a success for a moment.
|
||||||
const copied = ref('');
|
const copied = ref<{ text: string; ok: boolean }>();
|
||||||
let copiedTimer: number | undefined;
|
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 {
|
try {
|
||||||
await navigator.clipboard.writeText(text);
|
await navigator.clipboard.writeText(text);
|
||||||
} catch {
|
} 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;
|
copied.value = { text, ok: true };
|
||||||
clearTimeout(copiedTimer);
|
copiedTimer = window.setTimeout(() => (copied.value = undefined), 2000);
|
||||||
copiedTimer = window.setTimeout(() => (copied.value = ''), 2000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
|
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
|
||||||
@@ -161,11 +187,14 @@ let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
|
|||||||
let session: AbortController | undefined;
|
let session: AbortController | undefined;
|
||||||
const side = ref<'send' | 'receive'>();
|
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?.abort();
|
||||||
session = new AbortController();
|
session = new AbortController();
|
||||||
side.value = on;
|
side.value = on;
|
||||||
|
events.log(`--- ${what} ---`);
|
||||||
error.value = '';
|
error.value = '';
|
||||||
|
status.value = undefined;
|
||||||
check.value = undefined;
|
check.value = undefined;
|
||||||
confirmed.value = false;
|
confirmed.value = false;
|
||||||
sent.value = undefined;
|
sent.value = undefined;
|
||||||
@@ -213,7 +242,8 @@ function formatSize(bytes: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function onCreateOffer() {
|
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));
|
const result = await attempt(signal, createOffer(file.value!, sendEvents, signal));
|
||||||
if (!result) return;
|
if (!result) return;
|
||||||
offer.value = result.offer;
|
offer.value = result.offer;
|
||||||
@@ -227,13 +257,14 @@ function onAcceptAnswer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function onCreateAnswer() {
|
async function onCreateAnswer() {
|
||||||
const signal = begin('receive');
|
const signal = begin('receive', 'manual answer');
|
||||||
const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal));
|
const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal));
|
||||||
if (result) answer.value = result;
|
if (result) answer.value = result;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onShare() {
|
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));
|
const code = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal));
|
||||||
if (!code) return;
|
if (!code) return;
|
||||||
sendCode.value = code;
|
sendCode.value = code;
|
||||||
@@ -246,7 +277,7 @@ async function onShare() {
|
|||||||
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
|
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
|
||||||
|
|
||||||
function onReceive() {
|
function onReceive() {
|
||||||
const signal = begin('receive');
|
const signal = begin('receive', 'receive via tracker');
|
||||||
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal));
|
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal));
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
@@ -301,11 +332,17 @@ 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">
|
<div v-if="side === 'send' && phase" :data-phase="phase">
|
||||||
<progress id="send-progress" max="100" :value="percent(sent)" aria-label="Sent"></progress>
|
<p v-if="shared !== file" id="send-file">{{ shared!.name }}</p>
|
||||||
{{ percent(sent) }} %
|
<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>
|
||||||
<p v-if="error && side === 'send'" id="send-error" role="alert">{{ error }}</p>
|
</div>
|
||||||
|
|
||||||
<section>
|
<section>
|
||||||
<h3>Tracker</h3>
|
<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>
|
<label v-else for="send-code">Code, give this to the receiver, valid until {{ sendUntil }}:</label>
|
||||||
<div role="group">
|
<div role="group">
|
||||||
<output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output>
|
<output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output>
|
||||||
<button id="copy-send-code" type="button" data-copy :disabled="codeGone" @click="onCopy(sendCode)">
|
<button
|
||||||
{{ copied === sendCode ? 'Copied' : 'Copy' }}
|
id="copy-send-code"
|
||||||
|
type="button"
|
||||||
|
data-copy
|
||||||
|
:disabled="codeGone"
|
||||||
|
@click="onCopy(sendCode, 'send-code')"
|
||||||
|
>
|
||||||
|
{{ copyLabel(sendCode) }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<p v-if="copyFailed(sendCode)" role="alert">
|
||||||
|
The browser blocked copying. The code is selected, copy it yourself.
|
||||||
|
</p>
|
||||||
</template>
|
</template>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -331,9 +377,12 @@ function onReceive() {
|
|||||||
<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" type="button" data-copy @click="onCopy(offer)">
|
<button id="copy-offer" type="button" data-copy @click="onCopy(offer, 'offer')">
|
||||||
{{ copied === offer ? 'Copied' : 'Copy' }}
|
{{ copyLabel(offer) }}
|
||||||
</button>
|
</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>
|
<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" type="button" :disabled="!answerInput.trim()" @click="onAcceptAnswer">
|
<button id="accept-answer" type="button" :disabled="!answerInput.trim()" @click="onAcceptAnswer">
|
||||||
@@ -354,11 +403,16 @@ function onReceive() {
|
|||||||
</template>
|
</template>
|
||||||
<template v-else>The sender's file shows up here after the security check</template>
|
<template v-else>The sender's file shows up here after the security check</template>
|
||||||
</div>
|
</div>
|
||||||
<p v-if="received">
|
<div v-if="side === 'receive' && phase" :data-phase="phase">
|
||||||
<progress id="receive-progress" max="100" :value="percent(received)" aria-label="Received"></progress>
|
<div>
|
||||||
{{ percent(received) }} %
|
<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>
|
||||||
<p v-if="error && side === 'receive'" id="receive-error" role="alert">{{ error }}</p>
|
</div>
|
||||||
|
|
||||||
<section>
|
<section>
|
||||||
<h3>Tracker</h3>
|
<h3>Tracker</h3>
|
||||||
@@ -394,9 +448,12 @@ function onReceive() {
|
|||||||
<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" type="button" data-copy @click="onCopy(answer)">
|
<button id="copy-answer" type="button" data-copy @click="onCopy(answer, 'answer')">
|
||||||
{{ copied === answer ? 'Copied' : 'Copy' }}
|
{{ copyLabel(answer) }}
|
||||||
</button>
|
</button>
|
||||||
|
<p v-if="copyFailed(answer)" role="alert">
|
||||||
|
The browser blocked copying. The answer is selected, copy it yourself.
|
||||||
|
</p>
|
||||||
</template>
|
</template>
|
||||||
</section>
|
</section>
|
||||||
</details>
|
</details>
|
||||||
|
|||||||
+113
-21
@@ -63,8 +63,15 @@ export type Check = {
|
|||||||
reject: () => void;
|
reject: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// What a session is doing, see Events.status.
|
||||||
|
export type Phase = 'start' | 'wait' | 'retry' | 'transfer' | 'done' | 'stopped';
|
||||||
|
|
||||||
export type Events = {
|
export type Events = {
|
||||||
log: (message: string) => void;
|
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.
|
// Something the user has to act on, the session can't go on by itself. Not logged separately.
|
||||||
error: (message: string) => void;
|
error: (message: string) => void;
|
||||||
// Called on both sides once connected by the manual exchange, and without a check when it ended
|
// 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`;
|
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
|
// 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
|
// brute force with matching certificates. My local code must equal the peer's remote code and vice
|
||||||
// versa, otherwise someone interposed on the signaling.
|
// versa, otherwise someone interposed on the signaling.
|
||||||
@@ -438,12 +451,15 @@ function connected(
|
|||||||
pc: RTCPeerConnection,
|
pc: RTCPeerConnection,
|
||||||
channel: RTCDataChannel,
|
channel: RTCDataChannel,
|
||||||
via: string,
|
via: string,
|
||||||
|
peer: string,
|
||||||
events: Events,
|
events: Events,
|
||||||
next?: () => void,
|
next?: (reason: string) => void,
|
||||||
key?: CryptoKey,
|
key?: CryptoKey,
|
||||||
): Handshake {
|
): Handshake {
|
||||||
events.log(`connected via ${via}`);
|
events.log(`connected via ${via}`);
|
||||||
events.log('waiting for the security check');
|
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;
|
let done = false;
|
||||||
const end = (reason: string) => {
|
const end = (reason: string) => {
|
||||||
if (done) return;
|
if (done) return;
|
||||||
@@ -452,12 +468,12 @@ function connected(
|
|||||||
pc.close();
|
pc.close();
|
||||||
if (!next) return events.error(reason);
|
if (!next) return events.error(reason);
|
||||||
events.log(reason);
|
events.log(reason);
|
||||||
next();
|
next(reason);
|
||||||
};
|
};
|
||||||
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection.
|
// 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', () => {
|
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 {
|
return {
|
||||||
checked: key
|
checked: key
|
||||||
@@ -507,6 +523,7 @@ async function sendFile(
|
|||||||
events.progress(read, file.size);
|
events.progress(read, file.size);
|
||||||
} else if (message?.done === true && !stopped) {
|
} else if (message?.done === true && !stopped) {
|
||||||
events.log('delivered');
|
events.log('delivered');
|
||||||
|
events.status('done', 'Delivered');
|
||||||
events.progress(file.size, file.size);
|
events.progress(file.size, file.size);
|
||||||
stop();
|
stop();
|
||||||
} else if (typeof message?.error === 'string') {
|
} else if (typeof message?.error === 'string') {
|
||||||
@@ -529,7 +546,10 @@ async function sendFile(
|
|||||||
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
|
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
|
||||||
}
|
}
|
||||||
await handshake.checked;
|
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));
|
while (open() && !accepted) await new Promise<void>((resolve) => (wake = resolve));
|
||||||
if (!open()) return;
|
if (!open()) return;
|
||||||
|
|
||||||
@@ -537,11 +557,13 @@ async function sendFile(
|
|||||||
offered = true;
|
offered = true;
|
||||||
events.log(`offered ${file.name} (${file.size} bytes)`);
|
events.log(`offered ${file.name} (${file.size} bytes)`);
|
||||||
events.log('waiting for the receiver to download');
|
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));
|
while (open() && !sending) await new Promise<void>((resolve) => (wake = resolve));
|
||||||
if (!open()) return;
|
if (!open()) return;
|
||||||
|
|
||||||
handshake.start();
|
handshake.start();
|
||||||
events.log(`sending ${file.name}`);
|
events.log(`sending ${file.name}`);
|
||||||
|
events.status('transfer', 'Sending');
|
||||||
events.progress(0, file.size);
|
events.progress(0, file.size);
|
||||||
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
|
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
|
||||||
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
|
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
|
||||||
@@ -558,6 +580,7 @@ async function sendFile(
|
|||||||
channel.send(chunk);
|
channel.send(chunk);
|
||||||
}
|
}
|
||||||
events.log('sent');
|
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
|
// 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 === 'failed') fail('the service worker refused it');
|
||||||
if (data === 'finished') {
|
if (data === 'finished') {
|
||||||
events.log('download complete');
|
events.log('download complete');
|
||||||
|
events.status('done', 'Download complete');
|
||||||
events.progress(meta!.size, meta!.size);
|
events.progress(meta!.size, meta!.size);
|
||||||
reply({ done: true });
|
reply({ done: true });
|
||||||
}
|
}
|
||||||
if (data === 'cancelled' && !ended) {
|
if (data === 'cancelled' && !ended) {
|
||||||
events.log('download cancelled');
|
events.log('download cancelled');
|
||||||
|
events.status('stopped', 'Download cancelled');
|
||||||
reply({ error: 'download cancelled' });
|
reply({ error: 'download cancelled' });
|
||||||
}
|
}
|
||||||
ended = true;
|
ended = true;
|
||||||
@@ -708,6 +733,7 @@ function receiveFile(
|
|||||||
confirmed = true;
|
confirmed = true;
|
||||||
reply({ ok: true });
|
reply({ ok: true });
|
||||||
events.log('waiting for the sender');
|
events.log('waiting for the sender');
|
||||||
|
events.status('wait', 'Waiting for the sender');
|
||||||
});
|
});
|
||||||
|
|
||||||
function receivedAll() {
|
function receivedAll() {
|
||||||
@@ -724,6 +750,7 @@ function receiveFile(
|
|||||||
signal.addEventListener('abort', () => fail('stopped'), { once: true });
|
signal.addEventListener('abort', () => fail('stopped'), { once: true });
|
||||||
handshake.start();
|
handshake.start();
|
||||||
events.log(`receiving ${meta!.name}`);
|
events.log(`receiving ${meta!.name}`);
|
||||||
|
events.status('transfer', 'Receiving');
|
||||||
events.progress(0, meta!.size);
|
events.progress(0, meta!.size);
|
||||||
startDownload();
|
startDownload();
|
||||||
reply({ start: true });
|
reply({ start: true });
|
||||||
@@ -741,6 +768,7 @@ function receiveFile(
|
|||||||
}
|
}
|
||||||
meta = { name, size };
|
meta = { name, size };
|
||||||
events.log(`offered ${name} (${size} bytes)`);
|
events.log(`offered ${name} (${size} bytes)`);
|
||||||
|
events.status('wait', 'Click Download to save the file');
|
||||||
events.incoming({ name, size, download });
|
events.incoming({ name, size, download });
|
||||||
} else if (downloading && !complete) {
|
} else if (downloading && !complete) {
|
||||||
received += data.byteLength;
|
received += data.byteLength;
|
||||||
@@ -795,12 +823,15 @@ function failUnconnected(
|
|||||||
// The sender offers, the receiver answers, no tracker involved.
|
// The sender offers, the receiver answers, no tracker involved.
|
||||||
export async function createOffer(file: File, events: Events, signal: AbortSignal) {
|
export async function createOffer(file: File, events: Events, signal: AbortSignal) {
|
||||||
events = live(events, signal);
|
events = live(events, signal);
|
||||||
|
events.status('start', 'Creating the offer');
|
||||||
const pc = await createPeerConnection(signal);
|
const pc = await createPeerConnection(signal);
|
||||||
const channel = pc.createDataChannel('file');
|
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');
|
const wait = failUnconnected(pc, () => channel.readyState !== 'connecting', events, signal, 'receiver');
|
||||||
await pc.setLocalDescription();
|
await pc.setLocalDescription();
|
||||||
await gatherIce(pc);
|
await gatherIce(pc);
|
||||||
|
events.status('wait', 'Send the offer to the receiver and paste their answer below');
|
||||||
|
|
||||||
return {
|
return {
|
||||||
offer: btoa(pc.localDescription!.sdp),
|
offer: btoa(pc.localDescription!.sdp),
|
||||||
@@ -813,6 +844,7 @@ export async function createOffer(file: File, events: Events, signal: AbortSigna
|
|||||||
await pc.setRemoteDescription(description).catch(() => {
|
await pc.setRemoteDescription(description).catch(() => {
|
||||||
throw new Error('not a valid answer to this offer, copy all of it');
|
throw new Error('not a valid answer to this offer, copy all of it');
|
||||||
});
|
});
|
||||||
|
events.status('start', 'Connecting to the receiver');
|
||||||
wait(CONNECT_TIMEOUT);
|
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) {
|
export async function answerOffer(offer: string, events: ReceiveEvents, signal: AbortSignal) {
|
||||||
events = live(events, signal);
|
events = live(events, signal);
|
||||||
const description = decode(offer, 'offer');
|
const description = decode(offer, 'offer');
|
||||||
|
events.status('start', 'Creating the answer');
|
||||||
await downloadsReady();
|
await downloadsReady();
|
||||||
const pc = await createPeerConnection(signal);
|
const pc = await createPeerConnection(signal);
|
||||||
let opened = false;
|
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.
|
// The sender's file channel, anything more is none of ours.
|
||||||
if (opened) return;
|
if (opened) return;
|
||||||
opened = true;
|
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');
|
const wait = failUnconnected(pc, () => opened, events, signal, 'sender');
|
||||||
await pc.setRemoteDescription(description).catch(() => {
|
await pc.setRemoteDescription(description).catch(() => {
|
||||||
@@ -838,6 +871,7 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
|
|||||||
await pc.setLocalDescription();
|
await pc.setLocalDescription();
|
||||||
await gatherIce(pc);
|
await gatherIce(pc);
|
||||||
wait(TRACKER_WAIT);
|
wait(TRACKER_WAIT);
|
||||||
|
events.status('wait', 'Send the answer back to the sender, it connects once it has it');
|
||||||
|
|
||||||
return btoa(pc.localDescription!.sdp);
|
return btoa(pc.localDescription!.sdp);
|
||||||
}
|
}
|
||||||
@@ -924,6 +958,7 @@ function noTracker(trackers: (Tracker | undefined)[]) {
|
|||||||
// receiver connected by then still gets its turn.
|
// receiver connected by then still gets its turn.
|
||||||
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
||||||
events = live(events, signal);
|
events = live(events, signal);
|
||||||
|
events.status('start', 'Creating the code');
|
||||||
const code = randomCode();
|
const code = randomCode();
|
||||||
const { hash, key, sealing } = await secrets(code);
|
const { hash, key, sealing } = await secrets(code);
|
||||||
const peerId = randomBinary(20);
|
const peerId = randomBinary(20);
|
||||||
@@ -935,8 +970,17 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
|||||||
let expired = false;
|
let expired = false;
|
||||||
// The latest offer that came while busy, answered once that peer is out.
|
// The latest offer that came while busy, answered once that peer is out.
|
||||||
let waiting: (() => Promise<void>) | undefined;
|
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;
|
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.
|
// Without a tracker no further receiver can find the share.
|
||||||
const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive());
|
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);
|
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;
|
busy = false;
|
||||||
|
if (reason) failure = reason;
|
||||||
if (signal.aborted) return;
|
if (signal.aborted) return;
|
||||||
if (stranded()) return end(expired ? nobody() : noTracker(trackers));
|
if (stranded()) return end(expired ? nobody() : noTracker(trackers));
|
||||||
events.log('waiting for the next receiver');
|
events.log('waiting for the next receiver');
|
||||||
|
waitForReceiver();
|
||||||
const offer = waiting;
|
const offer = waiting;
|
||||||
waiting = undefined;
|
waiting = undefined;
|
||||||
void offer?.();
|
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 },
|
msg: { offer: { sdp: string }; peer_id: string; offer_id: string },
|
||||||
) {
|
) {
|
||||||
busy = true;
|
busy = true;
|
||||||
|
attempts++;
|
||||||
events.log(`offer via ${url}`);
|
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);
|
const pc = await createPeerConnection(signal);
|
||||||
// Until the data channel opens this ends the turn, from then on connected does.
|
// Until the data channel opens this ends the turn, from then on connected does.
|
||||||
let settled = false;
|
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) => {
|
const giveUp = (reason: string) => {
|
||||||
if (settled) return;
|
if (settled) return;
|
||||||
settled = true;
|
settled = true;
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
events.log(reason);
|
events.log(reason);
|
||||||
pc.close();
|
pc.close();
|
||||||
next();
|
next(problem);
|
||||||
};
|
};
|
||||||
const unconnected = () => {
|
const unconnected = () => {
|
||||||
if (settled) return;
|
if (settled) return;
|
||||||
hint = stunHint(pc, 'receiver');
|
hint = stunHint(pc, 'receiver') ?? BLOCKED;
|
||||||
giveUp(hint ? `receiver did not connect: ${hint}` : 'receiver did not connect');
|
problem = `could not connect to the receiver: ${hint}`;
|
||||||
|
giveUp(`receiver did not connect: ${hint}`);
|
||||||
};
|
};
|
||||||
const timeout = setTimeout(unconnected, CONNECT_TIMEOUT);
|
const timeout = setTimeout(unconnected, CONNECT_TIMEOUT);
|
||||||
pc.ondatachannel = ({ channel }) => {
|
pc.ondatachannel = ({ channel }) => {
|
||||||
if (settled) return;
|
if (settled) return;
|
||||||
settled = true;
|
settled = true;
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
const handshake = connected(pc, channel, url, events, next, key);
|
const handshake = connected(pc, channel, url, 'receiver', events, next, key);
|
||||||
const start = () => {
|
const start = () => {
|
||||||
handshake.start();
|
handshake.start();
|
||||||
shared = true;
|
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.
|
// The tracker at urls[i]. Receivers that come later walk on to the next one too, see receiveViaTracker.
|
||||||
function join(i: number) {
|
function join(i: number) {
|
||||||
const url = urls[i]!;
|
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(
|
const tracker = trackerSocket(
|
||||||
url,
|
url,
|
||||||
signal,
|
signal,
|
||||||
@@ -1053,6 +1108,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
|||||||
tracker.ws.onopen = () => {
|
tracker.ws.onopen = () => {
|
||||||
announce(tracker.ws, hash, peerId, { left: 0, event: 'started' });
|
announce(tracker.ws, hash, peerId, { left: 0, event: 'started' });
|
||||||
events.log(`waiting on ${url}`);
|
events.log(`waiting on ${url}`);
|
||||||
|
if (!busy) waitForReceiver();
|
||||||
};
|
};
|
||||||
trackers.push(tracker);
|
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.
|
// 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) {
|
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) {
|
||||||
events = live(events, signal);
|
events = live(events, signal);
|
||||||
|
events.status('start', 'Looking for the sender');
|
||||||
await downloadsReady();
|
await downloadsReady();
|
||||||
const { hash, key, sealing } = await secrets(code.trim());
|
const { hash, key, sealing } = await secrets(code.trim());
|
||||||
if (signal.aborted) return;
|
if (signal.aborted) return;
|
||||||
const peerId = randomBinary(20);
|
const peerId = randomBinary(20);
|
||||||
const urls = [...settings.trackers];
|
const urls = [...settings.trackers];
|
||||||
// The current offer per tracker by its place in urls, its connection once made, its socket only
|
// 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.
|
// until the answer came. lost: the socket closed before that. empty: its tracker has no seeder.
|
||||||
type Offer = { pc?: RTCPeerConnection; tracker?: Tracker; lost: boolean };
|
type Offer = { pc?: RTCPeerConnection; tracker?: Tracker; lost: boolean; empty?: boolean };
|
||||||
const offers = new Map<number, Offer>();
|
const offers = new Map<number, Offer>();
|
||||||
let isConnected = false;
|
let isConnected = false;
|
||||||
let started = false;
|
let started = false;
|
||||||
let expired = 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;
|
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 = () =>
|
const nobody = () =>
|
||||||
hint
|
hint
|
||||||
@@ -1106,11 +1175,13 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
|||||||
for (const { tracker } of offers.values()) tracker?.close();
|
for (const { tracker } of offers.values()) tracker?.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
const next = () => {
|
const next = (reason: string) => {
|
||||||
isConnected = false;
|
isConnected = false;
|
||||||
|
failure = reason;
|
||||||
if (signal.aborted) return;
|
if (signal.aborted) return;
|
||||||
if (expired) return end(nobody());
|
if (expired) return end(nobody());
|
||||||
events.log('looking again');
|
events.log('looking again');
|
||||||
|
looking('Looking for the sender');
|
||||||
for (const [i, { pc }] of offers) if (pc?.signalingState === 'closed') void offer(i);
|
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 = () => {
|
const unconnected = () => {
|
||||||
if (pc.signalingState === 'closed') return;
|
if (pc.signalingState === 'closed') return;
|
||||||
hint = stunHint(pc, 'sender');
|
hint = stunHint(pc, 'sender') ?? BLOCKED;
|
||||||
retry(hint ? `sender via ${url} did not connect: ${hint}` : `sender via ${url} did not connect`);
|
failure = `could not connect to the sender: ${hint}`;
|
||||||
|
retry(`sender via ${url} did not connect: ${hint}`);
|
||||||
|
looking('Looking for the sender');
|
||||||
};
|
};
|
||||||
channel.onopen = () => {
|
channel.onopen = () => {
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
if (isConnected || started) return pc.close();
|
if (isConnected || started) return pc.close();
|
||||||
isConnected = true;
|
isConnected = true;
|
||||||
const handshake = connected(pc, channel, url, events, next, key);
|
const handshake = connected(pc, channel, url, 'sender', events, next, key);
|
||||||
const start = () => {
|
const start = () => {
|
||||||
handshake.start();
|
handshake.start();
|
||||||
started = true;
|
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
|
// The tracker's reply to an announcement, complete counts the seeders. Without one the
|
||||||
// sender isn't here, or no longer.
|
// sender isn't here, or no longer.
|
||||||
if (msg.answer === undefined && msg.offer === undefined) {
|
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;
|
return;
|
||||||
}
|
}
|
||||||
if (msg.offer_id !== offerId || typeof msg.answer?.sdp !== 'string') 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 (pc.signalingState === 'closed' || !tracker.alive()) return;
|
||||||
if (answer === undefined) return events.log(`answer without the code via ${url}`);
|
if (answer === undefined) return events.log(`answer without the code via ${url}`);
|
||||||
events.log(`answer 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();
|
tracker.close();
|
||||||
timeout = setTimeout(unconnected, CONNECT_TIMEOUT);
|
timeout = setTimeout(unconnected, CONNECT_TIMEOUT);
|
||||||
pc.setRemoteDescription({ type: 'answer', sdp: answer }).catch(() => retry(`unusable answer via ${url}`));
|
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 = () => {
|
tracker.ws.onopen = () => {
|
||||||
hello('started');
|
hello('started');
|
||||||
events.log(`looking on ${url}`);
|
events.log(`looking on ${url}`);
|
||||||
|
looking(`Looking for the sender on ${host(url)}`);
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
// Closed in the meantime, nothing to report then.
|
// Closed in the meantime, nothing to report then.
|
||||||
|
|||||||
+86
-22
@@ -193,6 +193,10 @@ section p {
|
|||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
section p[role='alert'] {
|
||||||
|
color: var(--color-secondary-text);
|
||||||
|
}
|
||||||
|
|
||||||
header label {
|
header label {
|
||||||
color: var(--color-text);
|
color: var(--color-text);
|
||||||
}
|
}
|
||||||
@@ -377,54 +381,114 @@ label strong,
|
|||||||
overflow-wrap: anywhere;
|
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'] {
|
[data-phase] {
|
||||||
font-size: var(--text-sm);
|
--bar: var(--color-primary);
|
||||||
color: var(--color-secondary-text);
|
|
||||||
}
|
|
||||||
|
|
||||||
article > p[role='alert']::first-letter {
|
|
||||||
text-transform: uppercase;
|
|
||||||
}
|
|
||||||
|
|
||||||
p:has(> progress) {
|
|
||||||
display: flex;
|
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);
|
gap: var(--space-3);
|
||||||
font-size: var(--text-sm);
|
font-size: var(--text-sm);
|
||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
progress {
|
/* The send session's file, above its bar once the user picked another one */
|
||||||
flex: 1;
|
#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;
|
height: 0.5rem;
|
||||||
appearance: none;
|
|
||||||
border: none;
|
|
||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
background: var(--color-input);
|
background: var(--color-input);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
progress {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
appearance: none;
|
||||||
|
border: none;
|
||||||
|
background: none;
|
||||||
|
}
|
||||||
|
|
||||||
progress::-webkit-progress-bar {
|
progress::-webkit-progress-bar {
|
||||||
background: var(--color-input);
|
background: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
progress::-webkit-progress-value {
|
progress::-webkit-progress-value {
|
||||||
background: var(--color-primary);
|
background: var(--bar);
|
||||||
}
|
}
|
||||||
|
|
||||||
progress::-moz-progress-bar {
|
progress::-moz-progress-bar {
|
||||||
background: var(--color-primary);
|
background: var(--bar);
|
||||||
}
|
}
|
||||||
|
|
||||||
progress[value='100']::-webkit-progress-value {
|
progress:indeterminate {
|
||||||
background: var(--color-success);
|
width: 25%;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--bar);
|
||||||
|
animation: pass 2584ms linear infinite;
|
||||||
}
|
}
|
||||||
|
|
||||||
progress[value='100']::-moz-progress-bar {
|
progress:indeterminate::-moz-progress-bar {
|
||||||
background: var(--color-success);
|
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" */
|
/* Switch, like Pico's role="switch" */
|
||||||
|
|||||||
Reference in new issue
Block a user