Update index.html
Browse files12607 unmodified lines12608126091261012611126121261312614375 unmodified lines12990129911299212993129941299589 unmodified lines130851308613087130881308913090300 unmodified lines133911339213393133941339513396133971339875 unmodified lines1347413475134761347713478134791348013481134821348313484134851348613487134881348939 unmodified lines1352913530135311353213533135341353513536135371353827 unmodified lines13566135671356813569135701357113572135731357454 unmodified lines136291363013631136321363313634136351363613637435 unmodified lines1407314074140751407614077140789 unmodified lines1408814089140901409114092140931409414095140961409714098140991410014101141022 unmodified lines14105141061410714108141091411014 unmodified lines1412514126141271412814129141301413135 unmodified lines141671416814169141701417114172141733 unmodified lines1417714178141791418014181141821418312 unmodified lines1419614197141981419914200142011420221 unmodified lines14224142251422614227142281422931 unmodified lines14261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430512607 unmodified lines});</script><script>const CHUNK_SIZE = 64 * 1024;const ICE_SERVERS = [{ urls: 'stun:stun.l.google.com:19302' },{ urls: 'stun:stun1.l.google.com:19302' },375 unmodified linesreturn Math.random().toString(36).replace(/[^a-z0-9]/gi, '').slice(2, 8).toUpperCase().padEnd(6, 'X');}function badge() {const labels = {idle: t('badgeIdle'),89 unmodified lines</div>`;}// ---------------------------------------------------------------------// QR code (vendored qrcode-generator, no external network dependency)// ---------------------------------------------------------------------300 unmodified linessignaling?.close();deviceListener?.close();channel?.close();pc?.close();senderPeers.forEach((peer) => { peer.channel?.close(); peer.pc?.close(); });senderPeers = new Map();signaling = null;deviceListener = null;75 unmodified linesreturn pc;}function setupDataChannel(nextChannel) {channel = nextChannel;channel.binaryType = 'arraybuffer';channel.onopen = () => {setConnectionState('connected');channel.send(JSON.stringify({ kind: 'peer-info', ...localPeerInfo() }));reportConnectionPath(pc, (label) => { const el = $('#connPath'); if (el) el.textContent = label; });};channel.onclose = () => setConnectionState(allTransfersDone() ? 'done' : 'disconnected');channel.onmessage = (event) => handleDataMessage(event.data);}function allTransfersDone() {39 unmodified linesconst fileHandle = await dir.getFileHandle(pathSegments[pathSegments.length - 1]);const file = await fileHandle.getFile();dataChannel.send(JSON.stringify({ kind: 'meta', id: requestId, name: file.name, size: file.size, type: file.type }));for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {while (dataChannel.bufferedAmount > 8 * 1024 * 1024) await new Promise((resolve) => setTimeout(resolve, 20));const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();dataChannel.send(chunk);}dataChannel.send(JSON.stringify({ kind: 'done', id: requestId }));} catch (error) {27 unmodified linesdataChannel.onopen = () => {const entry = senderPeers.get(clientId);if (!entry) return;entry.state = 'connected';dataChannel.send(JSON.stringify({ kind: 'peer-info', ...localPeerInfo() }));if (sharedDirHandle) dataChannel.send(JSON.stringify({ kind: 'folder-shared', name: sharedDirHandle.name }));renderReceiversList();updateSendButtonState();reportConnectionPath(entry.pc, (label) => { entry.path = label; renderReceiversList(); });54 unmodified linesif (type === 'receiver-ready') {if (senderPeers.has(fromClientId)) return;const peerConnection = createSenderPeerConnection(fromClientId);const dataChannel = peerConnection.createDataChannel('files', { ordered: true });senderPeers.set(fromClientId, { pc: peerConnection, channel: dataChannel, name: null, path: '', state: 'connecting' });setupSenderDataChannel(fromClientId, dataChannel);renderReceiversList();await peerConnection.setLocalDescription(await peerConnection.createOffer());await waitForIceGathering(peerConnection);435 unmodified lines});}async function sendFiles() {const activePeers = [...senderPeers.values()].filter((peer) => peer.state === 'connected' && peer.channel?.readyState === 'open');if (!activePeers.length || !queued.length) return;9 unmodified linestransfers.set(file.id, { ...file, status: 'transferring' });renderTransfers(false);await Promise.all(activePeers.map(async (peer) => {peer.channel.send(JSON.stringify({ kind: 'meta', id: file.id, name: file.name, size: file.size, type: file.type }));for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {while (peer.channel.bufferedAmount > 8 * 1024 * 1024) await new Promise((resolve) => setTimeout(resolve, 20));const chunk = await file.file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();peer.channel.send(chunk);aggregateState.sentBytes += chunk.byteLength;renderAggregateProgress();}peer.channel.send(JSON.stringify({ kind: 'done', id: file.id }));}));2 unmodified linesrenderTransfers(false);}updateSendButtonState();notifyTransferComplete('notifyTransferSentBody');}14 unmodified lines$('#openBrowser').onclick = () => {browseState = { path: [], entries: [], loading: true };renderFileBrowser();channel?.send(JSON.stringify({ kind: 'browse-request', path: [] }));};}35 unmodified linesconst path = row.dataset.open.split('/');browseState = { path, entries: [], loading: true };renderFileBrowser();channel?.send(JSON.stringify({ kind: 'browse-request', path }));};});3 unmodified linesconst path = browseState.path.slice(0, depth);browseState = { path, entries: [], loading: true };renderFileBrowser();channel?.send(JSON.stringify({ kind: 'browse-request', path }));};});12 unmodified linesconst pathSegments = pathKey.split('/');const requestId = crypto.randomUUID();transfers.set(requestId, { id: requestId, name: pathSegments[pathSegments.length - 1], size: 0, transferred: 0, status: 'transferring' });channel?.send(JSON.stringify({ kind: 'file-request', path: pathSegments, id: requestId }));});selectedBrowsePicks.clear();renderTransfers(true);21 unmodified lines}).join('');}function handleDataMessage(data) {if (typeof data === 'string') {const message = JSON.parse(data);31 unmodified lines}if (message.kind === 'meta') {receiveBuffers.set(message.id, { ...message, chunks: [], received: 0 });transfers.set(message.id, { id: message.id, name: message.name, size: message.size, type: message.type, transferred: 0, status: 'transferring' });renderTransfers(true);}if (message.kind === 'done') {const received = receiveBuffers.get(message.id);const blob = new Blob(received.chunks, { type: received.type || 'application/octet-stream' });const url = URL.createObjectURL(blob);transfers.set(message.id, { ...transfers.get(message.id), transferred: received.size, status: 'done', url });renderTransfers(true);if (loadSettings().autoDownload) {const link = document.createElement('a');link.href = url;link.download = received.name;link.click();}if (aggregateState) {aggregateState.filesDone = (aggregateState.filesDone || 0) + 1;renderAggregateProgress();if (aggregateState.totalFiles && aggregateState.filesDone >= aggregateState.totalFiles) {notifyTransferComplete('notifyTransferReceivedBody');}}}return;}const active = [...receiveBuffers.values()].find((file) => file.received < file.size);if (!active) return;active.chunks.push(data);active.received += data.byteLength;const transfer = transfers.get(active.id);transfer.transferred = Math.min(active.received, active.size);renderTransfers(true);if (aggregateState) {aggregateState.sentBytes += data.byteLength;renderAggregateProgress();}}12607 unmodified lines12608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632375 unmodified lines13008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303489 unmodified lines1312413125131261312713128131291313013131300 unmodified lines1343213433134341343513436134371343813439134401344175 unmodified lines13517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354639 unmodified lines1358613587135881358913590135911359213593135941359513596135971359827 unmodified lines136261362713628136291363013631136321363313634136351363654 unmodified lines136911369213693136941369513696136971369813699435 unmodified lines1413514136141371413814139141401414114142141431414414145141461414714148141491415014151141529 unmodified lines1416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141852 unmodified lines1418814189141901419114192141931419414 unmodified lines1420914210142111421214213142141421535 unmodified lines142511425214253142541425514256142573 unmodified lines1426114262142631426414265142661426712 unmodified lines1428014281142821428314284142851428621 unmodified lines143081430914310143111431214313143141431531 unmodified lines143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440212607 unmodified lines});</script><script>const CHUNK_SIZE = 256 * 1024;const WHOLE_FILE_READ_LIMIT = 500 * 1024 * 1024; // 500MB — above this, stream from disk instead of buffering in memoryconst PARALLEL_CHANNELS = 3; // multiple data channels per receiver to work around per-channel SCTP throughput limitsconst CHUNK_ID_BYTES = 36; // length of a crypto.randomUUID() stringconst CHUNK_HEADER_BYTES = CHUNK_ID_BYTES + 8; // + 8-byte float64 offsetfunction packChunk(id, offset, arrayBuffer) {const combined = new Uint8Array(CHUNK_HEADER_BYTES + arrayBuffer.byteLength);combined.set(new TextEncoder().encode(id), 0);new DataView(combined.buffer).setFloat64(CHUNK_ID_BYTES, offset, true);combined.set(new Uint8Array(arrayBuffer), CHUNK_HEADER_BYTES);return combined.buffer;}function unpackChunk(buffer) {const id = new TextDecoder().decode(buffer.slice(0, CHUNK_ID_BYTES));const offset = new DataView(buffer).getFloat64(CHUNK_ID_BYTES, true);return { id, offset, data: buffer.slice(CHUNK_HEADER_BYTES) };}const ICE_SERVERS = [{ urls: 'stun:stun.l.google.com:19302' },{ urls: 'stun:stun1.l.google.com:19302' },375 unmodified linesreturn Math.random().toString(36).replace(/[^a-z0-9]/gi, '').slice(2, 8).toUpperCase().padEnd(6, 'X');}function throttle(fn, wait) {let last = 0;let timer = null;return (...args) => {const now = Date.now();const remaining = wait - (now - last);if (remaining <= 0) {clearTimeout(timer);timer = null;last = now;fn(...args);} else if (!timer) {timer = setTimeout(() => {last = Date.now();timer = null;fn(...args);}, remaining);}};}function badge() {const labels = {idle: t('badgeIdle'),89 unmodified lines</div>`;}const throttledRenderAggregateProgress = throttle(renderAggregateProgress, 150);// ---------------------------------------------------------------------// QR code (vendored qrcode-generator, no external network dependency)// ---------------------------------------------------------------------300 unmodified linessignaling?.close();deviceListener?.close();channel?.close();receiverChannels.forEach((ch) => ch.close());receiverChannels = [];pc?.close();senderPeers.forEach((peer) => { peer.channels?.forEach((ch) => ch.close()); peer.pc?.close(); });senderPeers = new Map();signaling = null;deviceListener = null;75 unmodified linesreturn pc;}let receiverChannels = [];function sendControl(message) {const target = receiverChannels.find((ch) => ch.readyState === 'open') || channel;target?.send(JSON.stringify(message));}function setupDataChannel(nextChannel) {receiverChannels.push(nextChannel);channel = nextChannel;nextChannel.binaryType = 'arraybuffer';nextChannel.onopen = () => {if (receiverChannels.filter((ch) => ch.readyState === 'open').length === 1) {setConnectionState('connected');sendControl({ kind: 'peer-info', ...localPeerInfo() });reportConnectionPath(pc, (label) => { const el = $('#connPath'); if (el) el.textContent = label; });}};nextChannel.onclose = () => {if (!receiverChannels.some((ch) => ch.readyState === 'open')) {setConnectionState(allTransfersDone() ? 'done' : 'disconnected');}};nextChannel.onmessage = (event) => handleDataMessage(event.data);}function allTransfersDone() {39 unmodified linesconst fileHandle = await dir.getFileHandle(pathSegments[pathSegments.length - 1]);const file = await fileHandle.getFile();dataChannel.send(JSON.stringify({ kind: 'meta', id: requestId, name: file.name, size: file.size, type: file.type }));const wholeBuffer = file.size <= WHOLE_FILE_READ_LIMIT ? await file.arrayBuffer() : null;for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {await waitForBufferedAmountLow(dataChannel);const rawChunk = wholeBuffer? wholeBuffer.slice(offset, offset + CHUNK_SIZE): await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();dataChannel.send(packChunk(requestId, offset, rawChunk));}dataChannel.send(JSON.stringify({ kind: 'done', id: requestId }));} catch (error) {27 unmodified linesdataChannel.onopen = () => {const entry = senderPeers.get(clientId);if (!entry) return;entry.openChannels = (entry.openChannels || 0) + 1;if (entry.openChannels < entry.channels.length) return; // wait until every parallel channel is upentry.state = 'connected';entry.channel.send(JSON.stringify({ kind: 'peer-info', ...localPeerInfo() }));if (sharedDirHandle) entry.channel.send(JSON.stringify({ kind: 'folder-shared', name: sharedDirHandle.name }));renderReceiversList();updateSendButtonState();reportConnectionPath(entry.pc, (label) => { entry.path = label; renderReceiversList(); });54 unmodified linesif (type === 'receiver-ready') {if (senderPeers.has(fromClientId)) return;const peerConnection = createSenderPeerConnection(fromClientId);const channels = Array.from({ length: PARALLEL_CHANNELS }, (_, i) => peerConnection.createDataChannel(`files-${i}`, { ordered: true }));senderPeers.set(fromClientId, { pc: peerConnection, channels, channel: channels[0], openChannels: 0, name: null, path: '', state: 'connecting' });channels.forEach((ch) => setupSenderDataChannel(fromClientId, ch));renderReceiversList();await peerConnection.setLocalDescription(await peerConnection.createOffer());await waitForIceGathering(peerConnection);435 unmodified lines});}function waitForBufferedAmountLow(dataChannel, threshold = 8 * 1024 * 1024) {if (dataChannel.bufferedAmount <= threshold) return Promise.resolve();return new Promise((resolve) => {dataChannel.bufferedAmountLowThreshold = threshold;const onLow = () => {dataChannel.removeEventListener('bufferedamountlow', onLow);resolve();};dataChannel.addEventListener('bufferedamountlow', onLow);});}async function sendFiles() {const activePeers = [...senderPeers.values()].filter((peer) => peer.state === 'connected' && peer.channel?.readyState === 'open');if (!activePeers.length || !queued.length) return;9 unmodified linestransfers.set(file.id, { ...file, status: 'transferring' });renderTransfers(false);// Read once and share the buffer across every receiver instead of re-reading// the same bytes from disk per chunk, per peer — this was the main bottleneck.const wholeBuffer = file.size <= WHOLE_FILE_READ_LIMIT ? await file.file.arrayBuffer() : null;await Promise.all(activePeers.map(async (peer) => {peer.channel.send(JSON.stringify({ kind: 'meta', id: file.id, name: file.name, size: file.size, type: file.type }));const channels = peer.channels && peer.channels.length ? peer.channels : [peer.channel];await Promise.all(channels.map(async (ch, channelIndex) => {for (let offset = channelIndex * CHUNK_SIZE; offset < file.size; offset += CHUNK_SIZE * channels.length) {await waitForBufferedAmountLow(ch);const rawChunk = wholeBuffer? wholeBuffer.slice(offset, offset + CHUNK_SIZE): await file.file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();ch.send(packChunk(file.id, offset, rawChunk));aggregateState.sentBytes += rawChunk.byteLength;throttledRenderAggregateProgress();}}));peer.channel.send(JSON.stringify({ kind: 'done', id: file.id }));}));2 unmodified linesrenderTransfers(false);}renderAggregateProgress();updateSendButtonState();notifyTransferComplete('notifyTransferSentBody');}14 unmodified lines$('#openBrowser').onclick = () => {browseState = { path: [], entries: [], loading: true };renderFileBrowser();sendControl({ kind: 'browse-request', path: [] });};}35 unmodified linesconst path = row.dataset.open.split('/');browseState = { path, entries: [], loading: true };renderFileBrowser();sendControl({ kind: 'browse-request', path });};});3 unmodified linesconst path = browseState.path.slice(0, depth);browseState = { path, entries: [], loading: true };renderFileBrowser();sendControl({ kind: 'browse-request', path });};});12 unmodified linesconst pathSegments = pathKey.split('/');const requestId = crypto.randomUUID();transfers.set(requestId, { id: requestId, name: pathSegments[pathSegments.length - 1], size: 0, transferred: 0, status: 'transferring' });sendControl({ kind: 'file-request', path: pathSegments, id: requestId });});selectedBrowsePicks.clear();renderTransfers(true);21 unmodified lines}).join('');}const throttledRenderTransfers = throttle(() => renderTransfers(true), 150);function handleDataMessage(data) {if (typeof data === 'string') {const message = JSON.parse(data);31 unmodified lines}if (message.kind === 'meta') {receiveBuffers.set(message.id, { ...message, buffer: new Uint8Array(message.size), received: 0, doneSignaled: false });transfers.set(message.id, { id: message.id, name: message.name, size: message.size, type: message.type, transferred: 0, status: 'transferring' });renderTransfers(true);}if (message.kind === 'done') {const received = receiveBuffers.get(message.id);if (!received) return;received.doneSignaled = true;if (received.received >= received.size) finalizeReceivedFile(message.id);}return;}const { id, offset, data: payload } = unpackChunk(data);const received = receiveBuffers.get(id);if (!received) return;received.buffer.set(new Uint8Array(payload), offset);received.received += payload.byteLength;const transfer = transfers.get(id);if (transfer) transfer.transferred = Math.min(received.received, received.size);throttledRenderTransfers();if (aggregateState) {aggregateState.sentBytes += payload.byteLength;throttledRenderAggregateProgress();}if (received.doneSignaled && received.received >= received.size) finalizeReceivedFile(id);}function finalizeReceivedFile(id) {const received = receiveBuffers.get(id);if (!received || received.finalized) return;received.finalized = true;const blob = new Blob([received.buffer], { type: received.type || 'application/octet-stream' });const url = URL.createObjectURL(blob);transfers.set(id, { ...transfers.get(id), transferred: received.size, status: 'done', url });renderTransfers(true);if (loadSettings().autoDownload) {const link = document.createElement('a');link.href = url;link.download = received.name;link.click();}if (aggregateState) {aggregateState.filesDone = (aggregateState.filesDone || 0) + 1;renderAggregateProgress();if (aggregateState.totalFiles && aggregateState.filesDone >= aggregateState.totalFiles) {notifyTransferComplete('notifyTransferReceivedBody');}}}
index.html+150-53