Show how a session is doing on the progress bar
Each side's bar now shows the session's phase by color and movement, with a short line below saying what is going on: a sweep while connecting, a pulse while someone has to act, a slow pink sweep while retrying after a failure (with the reason and the attempt), then the transfer, done, stopped or error. A receiver whose code no tracker knows says so right away instead of after 6 minutes, and a connection that fails though both sides have a public address names a blocking network as the likely reason. The log marks where each session starts. The send card names the session's file once another one is picked, and a blocked clipboard is shown inline with the text selected for copying by hand. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
02668de602
commit
f7e8999439
4 files changed
+348
-67
No files matched your search
+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, give them the code');
|
||||
|
||||
// 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.
|
||||
|
||||
Reference in new issue
Block a user