| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
import {getById, h, writeDebug, writeError, writeInfo} from "/common.module.js"; |
| 9 |
import {QRCode} from "/qrcode.js"; |
| 10 |
|
| 11 |
|
| 12 |
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; |
| 13 |
const CODE_LENGTH = 12; |
| 14 |
const CODE_PATTERN = /^[0-9A-HJKMNP-TV-Z]{12}$/; |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
const CHUNK = 64 * 1024; |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
const HIGH_WATER = 8 * 1024 * 1024; |
| 24 |
const LOW_WATER = 1 * 1024 * 1024; |
| 25 |
|
| 26 |
const state = getById("state"); |
| 27 |
const pairing = getById("pairing"); |
| 28 |
const linkField = getById("link"); |
| 29 |
const codeText = getById("code"); |
| 30 |
const copyButton = getById("copy"); |
| 31 |
const joinForm = getById("joinForm"); |
| 32 |
const joinInput = getById("joinCode"); |
| 33 |
const fileInput = getById("files"); |
| 34 |
const dropZone = getById("drop"); |
| 35 |
const outgoing = getById("outgoing"); |
| 36 |
const incoming = getById("incoming"); |
| 37 |
const nothingYet = getById("nothingYet"); |
| 38 |
|
| 39 |
|
| 40 |
let connection = null; |
| 41 |
|
| 42 |
let channel = null; |
| 43 |
|
| 44 |
|
| 45 |
let signallingEnded = false; |
| 46 |
|
| 47 |
|
| 48 |
let everConnected = false; |
| 49 |
|
| 50 |
|
| 51 |
let earlyCandidates = []; |
| 52 |
|
| 53 |
|
| 54 |
let arriving = null; |
| 55 |
|
| 56 |
|
| 57 |
let queue = Promise.resolve(); |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
function newCode() { |
| 63 |
const bytes = new Uint8Array(CODE_LENGTH); |
| 64 |
crypto.getRandomValues(bytes); |
| 65 |
|
| 66 |
|
| 67 |
return Array.from(bytes, byte => ALPHABET[byte & 31]).join(""); |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
function normalise(text) { |
| 72 |
return text.toUpperCase().replace(/[^0-9A-Z]/g, "") |
| 73 |
.replace(/[IL]/g, "1") |
| 74 |
.replace(/O/g, "0"); |
| 75 |
} |
| 76 |
|
| 77 |
function group(code) { |
| 78 |
return code.replace(/(.{4})(?=.)/g, "$1-"); |
| 79 |
} |
| 80 |
|
| 81 |
const fromHash = normalise(location.hash.slice(1)); |
| 82 |
const room = CODE_PATTERN.test(fromHash) ? fromHash : newCode(); |
| 83 |
|
| 84 |
const shareUrl = new URL(location.href); |
| 85 |
shareUrl.hash = room; |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
if (room !== fromHash) history.replaceState(null, "", shareUrl.href); |
| 92 |
|
| 93 |
linkField.value = shareUrl.href; |
| 94 |
codeText.textContent = group(room); |
| 95 |
new QRCode("qrcode", shareUrl.href); |
| 96 |
|
| 97 |
copyButton.addEventListener("click", async () => { |
| 98 |
try { |
| 99 |
await navigator.clipboard.writeText(shareUrl.href); |
| 100 |
writeInfo("Link copied."); |
| 101 |
} catch { |
| 102 |
|
| 103 |
linkField.select(); |
| 104 |
writeError("Could not copy — the link is selected instead."); |
| 105 |
} |
| 106 |
}); |
| 107 |
|
| 108 |
joinForm.addEventListener("submit", event => { |
| 109 |
event.preventDefault(); |
| 110 |
const code = normalise(joinInput.value); |
| 111 |
|
| 112 |
if (!CODE_PATTERN.test(code)) { |
| 113 |
writeError("That is not a code — twelve letters and digits, no I, L, O or U."); |
| 114 |
return; |
| 115 |
} |
| 116 |
if (code === room) return; |
| 117 |
|
| 118 |
location.hash = code; |
| 119 |
}); |
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
addEventListener("hashchange", () => location.reload()); |
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
if (!window.isSecureContext || !("RTCPeerConnection" in window)) { |
| 132 |
setState("This browser will not do WebRTC here — it needs https (or localhost)."); |
| 133 |
throw new Error("WebRTC unavailable"); |
| 134 |
} |
| 135 |
|
| 136 |
const iceUrls = JSON.parse(getById("ice").dataset.servers); |
| 137 |
const rtcConfig = {iceServers: iceUrls.length > 0 ? [{urls: iceUrls}] : []}; |
| 138 |
|
| 139 |
const socket = new WebSocket(`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/send/${room}`); |
| 140 |
|
| 141 |
socket.addEventListener("open", () => writeDebug("Signalling socket open.")); |
| 142 |
socket.addEventListener("error", () => writeError("The signalling socket failed.")); |
| 143 |
socket.addEventListener("close", () => { |
| 144 |
writeDebug("Signalling socket closed."); |
| 145 |
|
| 146 |
|
| 147 |
if (!signallingEnded && channel?.readyState !== "open") { |
| 148 |
setState("Lost the signalling socket. Reload to try again."); |
| 149 |
} |
| 150 |
}); |
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
let handling = Promise.resolve(); |
| 155 |
|
| 156 |
socket.addEventListener("message", event => { |
| 157 |
let message; |
| 158 |
try { |
| 159 |
message = JSON.parse(event.data); |
| 160 |
} catch { |
| 161 |
writeError("Unreadable signalling message."); |
| 162 |
return; |
| 163 |
} |
| 164 |
|
| 165 |
handling = handling.then(() => onSignal(message)).catch(error => writeError(error)); |
| 166 |
}); |
| 167 |
|
| 168 |
async function onSignal(message) { |
| 169 |
switch (message.type) { |
| 170 |
case "waiting": |
| 171 |
setState("Waiting for the other side — send them the link."); |
| 172 |
break; |
| 173 |
|
| 174 |
case "ready": |
| 175 |
setState("Other side found; connecting…"); |
| 176 |
await connect(message.initiator); |
| 177 |
break; |
| 178 |
|
| 179 |
case "peer-left": |
| 180 |
if (channel?.readyState === "open") { |
| 181 |
|
| 182 |
writeInfo("The other side's signalling link dropped. The transfer link is still up."); |
| 183 |
} else { |
| 184 |
teardown(); |
| 185 |
setState("The other side left. Waiting for someone to join."); |
| 186 |
} |
| 187 |
break; |
| 188 |
|
| 189 |
case "busy": |
| 190 |
signallingEnded = true; |
| 191 |
setState("That room already has two browsers in it. Start a fresh one from /Send."); |
| 192 |
break; |
| 193 |
|
| 194 |
case "offer": |
| 195 |
await connect(false); |
| 196 |
await connection.setRemoteDescription(message.sdp); |
| 197 |
await connection.setLocalDescription(await connection.createAnswer()); |
| 198 |
signal({type: "answer", sdp: connection.localDescription}); |
| 199 |
await flushCandidates(); |
| 200 |
break; |
| 201 |
|
| 202 |
case "answer": |
| 203 |
await connection.setRemoteDescription(message.sdp); |
| 204 |
await flushCandidates(); |
| 205 |
break; |
| 206 |
|
| 207 |
case "ice": |
| 208 |
|
| 209 |
if (connection?.remoteDescription) await connection.addIceCandidate(message.candidate); |
| 210 |
else earlyCandidates.push(message.candidate); |
| 211 |
break; |
| 212 |
|
| 213 |
default: |
| 214 |
writeDebug(`Ignoring signalling message: ${message.type}`); |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
function signal(message) { |
| 219 |
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message)); |
| 220 |
} |
| 221 |
|
| 222 |
async function flushCandidates() { |
| 223 |
const candidates = earlyCandidates; |
| 224 |
earlyCandidates = []; |
| 225 |
for (const candidate of candidates) await connection.addIceCandidate(candidate); |
| 226 |
} |
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
async function connect(initiator) { |
| 236 |
if (connection) return; |
| 237 |
|
| 238 |
connection = new RTCPeerConnection(rtcConfig); |
| 239 |
|
| 240 |
connection.addEventListener("icecandidate", event => { |
| 241 |
if (event.candidate) signal({type: "ice", candidate: event.candidate}); |
| 242 |
}); |
| 243 |
|
| 244 |
connection.addEventListener("connectionstatechange", () => { |
| 245 |
|
| 246 |
const current = connection?.connectionState; |
| 247 |
if (!current) return; |
| 248 |
|
| 249 |
writeDebug(`Connection: ${current}`); |
| 250 |
|
| 251 |
if (current === "connected") { |
| 252 |
everConnected = true; |
| 253 |
return; |
| 254 |
} |
| 255 |
|
| 256 |
if (current !== "failed" && current !== "closed") return; |
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
const lost = everConnected; |
| 262 |
teardown(); |
| 263 |
setState(lost |
| 264 |
? "The connection dropped. Waiting for the other side to come back." |
| 265 |
: "Could not find a route between the two browsers."); |
| 266 |
}); |
| 267 |
|
| 268 |
|
| 269 |
connection.addEventListener("datachannel", event => attach(event.channel)); |
| 270 |
|
| 271 |
if (initiator) { |
| 272 |
attach(connection.createDataChannel("files", {ordered: true})); |
| 273 |
await connection.setLocalDescription(await connection.createOffer()); |
| 274 |
signal({type: "offer", sdp: connection.localDescription}); |
| 275 |
} |
| 276 |
} |
| 277 |
|
| 278 |
function teardown() { |
| 279 |
channel?.close(); |
| 280 |
connection?.close(); |
| 281 |
channel = null; |
| 282 |
connection = null; |
| 283 |
earlyCandidates = []; |
| 284 |
arriving = null; |
| 285 |
everConnected = false; |
| 286 |
fileInput.disabled = true; |
| 287 |
pairing.hidden = false; |
| 288 |
} |
| 289 |
|
| 290 |
function attach(dataChannel) { |
| 291 |
channel = dataChannel; |
| 292 |
channel.binaryType = "arraybuffer"; |
| 293 |
channel.bufferedAmountLowThreshold = LOW_WATER; |
| 294 |
|
| 295 |
channel.addEventListener("open", () => { |
| 296 |
fileInput.disabled = false; |
| 297 |
pairing.hidden = true; |
| 298 |
setState("Connected. Pick a file."); |
| 299 |
describeRoute(); |
| 300 |
}); |
| 301 |
|
| 302 |
channel.addEventListener("close", () => { |
| 303 |
fileInput.disabled = true; |
| 304 |
pairing.hidden = false; |
| 305 |
setState("The connection closed."); |
| 306 |
}); |
| 307 |
|
| 308 |
channel.addEventListener("error", event => writeError(event.error ?? "Data channel error.")); |
| 309 |
channel.addEventListener("message", onData); |
| 310 |
} |
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
async function describeRoute() { |
| 317 |
try { |
| 318 |
const stats = await connection.getStats(); |
| 319 |
let pair = null; |
| 320 |
stats.forEach(report => { |
| 321 |
if (report.type === "candidate-pair" && report.state === "succeeded") pair = report; |
| 322 |
}); |
| 323 |
if (!pair) return; |
| 324 |
|
| 325 |
const local = stats.get(pair.localCandidateId)?.candidateType; |
| 326 |
const remote = stats.get(pair.remoteCandidateId)?.candidateType; |
| 327 |
const relayed = local === "relay" || remote === "relay"; |
| 328 |
writeInfo(`Route: ${local} to ${remote}${relayed ? " (relayed)" : " (direct)"}.`); |
| 329 |
} catch (error) { |
| 330 |
writeDebug(`No route stats: ${error}`); |
| 331 |
} |
| 332 |
} |
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
fileInput.addEventListener("change", () => { |
| 338 |
enqueue(fileInput.files); |
| 339 |
|
| 340 |
fileInput.value = ""; |
| 341 |
}); |
| 342 |
|
| 343 |
for (const type of ["dragenter", "dragover"]) { |
| 344 |
dropZone.addEventListener(type, event => { |
| 345 |
event.preventDefault(); |
| 346 |
dropZone.classList.add("over"); |
| 347 |
}); |
| 348 |
} |
| 349 |
|
| 350 |
for (const type of ["dragleave", "drop"]) { |
| 351 |
dropZone.addEventListener(type, event => { |
| 352 |
event.preventDefault(); |
| 353 |
dropZone.classList.remove("over"); |
| 354 |
}); |
| 355 |
} |
| 356 |
|
| 357 |
dropZone.addEventListener("drop", event => { |
| 358 |
if (channel?.readyState !== "open") { |
| 359 |
writeError("Not connected yet."); |
| 360 |
return; |
| 361 |
} |
| 362 |
if (event.dataTransfer?.files?.length) enqueue(event.dataTransfer.files); |
| 363 |
}); |
| 364 |
|
| 365 |
function enqueue(files) { |
| 366 |
for (const file of files) { |
| 367 |
queue = queue.then(() => sendFile(file)).catch(error => writeError(error)); |
| 368 |
} |
| 369 |
} |
| 370 |
|
| 371 |
async function sendFile(file) { |
| 372 |
if (channel?.readyState !== "open") { |
| 373 |
writeError(`Not connected — ${file.name} was not sent.`); |
| 374 |
return; |
| 375 |
} |
| 376 |
|
| 377 |
const row = addRow(outgoing, file.name, file.size); |
| 378 |
channel.send(JSON.stringify({kind: "start", name: file.name, size: file.size, mime: file.type})); |
| 379 |
|
| 380 |
|
| 381 |
const limit = Math.min(CHUNK, connection.sctp?.maxMessageSize || CHUNK); |
| 382 |
|
| 383 |
for (let offset = 0; offset < file.size; offset += limit) { |
| 384 |
const chunk = await file.slice(offset, offset + limit).arrayBuffer(); |
| 385 |
await drain(); |
| 386 |
|
| 387 |
if (channel.readyState !== "open") { |
| 388 |
row.fail("interrupted"); |
| 389 |
return; |
| 390 |
} |
| 391 |
|
| 392 |
channel.send(chunk); |
| 393 |
|
| 394 |
row.progress(Math.max(0, offset + chunk.byteLength - channel.bufferedAmount)); |
| 395 |
} |
| 396 |
|
| 397 |
channel.send(JSON.stringify({kind: "end"})); |
| 398 |
row.done("sent"); |
| 399 |
} |
| 400 |
|
| 401 |
|
| 402 |
function drain() { |
| 403 |
if (channel.bufferedAmount < HIGH_WATER) return Promise.resolve(); |
| 404 |
|
| 405 |
return new Promise(resolve => { |
| 406 |
const go = () => { |
| 407 |
channel.removeEventListener("bufferedamountlow", go); |
| 408 |
channel.removeEventListener("close", go); |
| 409 |
resolve(); |
| 410 |
}; |
| 411 |
channel.addEventListener("bufferedamountlow", go); |
| 412 |
|
| 413 |
|
| 414 |
channel.addEventListener("close", go); |
| 415 |
}); |
| 416 |
} |
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
function onData(event) { |
| 422 |
if (typeof event.data === "string") { |
| 423 |
onControl(JSON.parse(event.data)); |
| 424 |
return; |
| 425 |
} |
| 426 |
|
| 427 |
if (!arriving) { |
| 428 |
writeError("A chunk arrived with no file to put it in."); |
| 429 |
return; |
| 430 |
} |
| 431 |
|
| 432 |
arriving.parts.push(event.data); |
| 433 |
arriving.received += event.data.byteLength; |
| 434 |
arriving.row.progress(arriving.received); |
| 435 |
} |
| 436 |
|
| 437 |
function onControl(message) { |
| 438 |
if (message.kind === "start") { |
| 439 |
nothingYet.hidden = true; |
| 440 |
arriving = { |
| 441 |
name: message.name, |
| 442 |
size: message.size, |
| 443 |
mime: message.mime, |
| 444 |
parts: [], |
| 445 |
received: 0, |
| 446 |
row: addRow(incoming, message.name, message.size), |
| 447 |
}; |
| 448 |
return; |
| 449 |
} |
| 450 |
|
| 451 |
if (message.kind === "end") { |
| 452 |
if (!arriving) return; |
| 453 |
|
| 454 |
if (arriving.received !== arriving.size) { |
| 455 |
writeError(`${arriving.name} came to ${arriving.received} bytes, not ${arriving.size}.`); |
| 456 |
} |
| 457 |
|
| 458 |
|
| 459 |
|
| 460 |
const blob = new Blob(arriving.parts, {type: arriving.mime || "application/octet-stream"}); |
| 461 |
arriving.row.finish(blob, arriving.name); |
| 462 |
arriving = null; |
| 463 |
} |
| 464 |
} |
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
|
| 470 |
function addRow(list, name, size) { |
| 471 |
const label = h("span", {class: "transfer-name"}, name); |
| 472 |
const bar = h("progress", {max: String(size || 1), value: "0"}); |
| 473 |
const status = h("span", {class: "transfer-status"}, "0%"); |
| 474 |
const row = h("li", {class: "transfer"}, [ |
| 475 |
label, |
| 476 |
h("span", {class: "transfer-size"}, formatSize(size)), |
| 477 |
bar, |
| 478 |
status, |
| 479 |
]); |
| 480 |
|
| 481 |
list.appendChild(row); |
| 482 |
|
| 483 |
return { |
| 484 |
progress(done) { |
| 485 |
bar.value = done; |
| 486 |
status.textContent = size ? `${Math.floor(done / size * 100)}%` : "0%"; |
| 487 |
}, |
| 488 |
done(text) { |
| 489 |
bar.value = bar.max; |
| 490 |
status.textContent = text; |
| 491 |
}, |
| 492 |
finish(blob, filename) { |
| 493 |
bar.value = bar.max; |
| 494 |
status.textContent = "ready"; |
| 495 |
row.replaceChild( |
| 496 |
h("a", {class: "transfer-name", href: URL.createObjectURL(blob), download: filename}, name), |
| 497 |
label); |
| 498 |
}, |
| 499 |
fail(text) { |
| 500 |
status.textContent = text; |
| 501 |
row.classList.add("failed"); |
| 502 |
}, |
| 503 |
}; |
| 504 |
} |
| 505 |
|
| 506 |
function formatSize(bytes) { |
| 507 |
const units = ["B", "kB", "MB", "GB", "TB"]; |
| 508 |
let size = bytes; |
| 509 |
let unit = 0; |
| 510 |
while (size >= 1000 && unit < units.length - 1) { |
| 511 |
size /= 1000; |
| 512 |
unit++; |
| 513 |
} |
| 514 |
return `${unit === 0 ? size : size.toFixed(1)} ${units[unit]}`; |
| 515 |
} |
| 516 |
|
| 517 |
function setState(text) { |
| 518 |
state.textContent = text; |
| 519 |
} |