diff --git a/connector/src/main.rs b/connector/src/main.rs index 3a1fa95..2b4a999 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -1,6 +1,7 @@ use std::borrow::Cow; use std::collections::{BTreeMap, HashMap, HashSet}; use std::str; +use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use anyhow::Result; @@ -44,6 +45,22 @@ const MAX_UPLOAD_BYTES: u64 = 24 << 20; /// line per file made the Node gateway hold several copies of it at once and /// run out of heap (2026-10-11). const TRANSFER_CHUNK_BYTES: usize = 192 << 10; +// File transfer bandwidth caps in bytes/s (0 = unlimited), set via the +// "ftlimit " stdin command. Read by the spawned transfer tasks. +static FT_LIMIT_UP: AtomicU64 = AtomicU64::new(0); +static FT_LIMIT_DOWN: AtomicU64 = AtomicU64::new(0); + +/// Sleeps long enough that `bytes` took at least bytes/limit seconds. +async fn ft_pace(limit: &AtomicU64, bytes: usize, started: std::time::Instant) { + let limit = limit.load(Ordering::Relaxed); + if limit == 0 { + return; + } + let target = Duration::from_secs_f64(bytes as f64 / limit as f64); + if let Some(rest) = target.checked_sub(started.elapsed()) { + tokio::time::sleep(rest).await; + } +} /// Half-received chunked uploads per connection - each can hold up to /// MAX_UPLOAD_BYTES until it completes. const MAX_PARTIAL_UPLOADS: usize = 4; @@ -1445,6 +1462,10 @@ async fn run(args: Args) -> Result<()> { let (mode, ids) = rest.split_once(';').unwrap_or((rest, "")); whisper_block_default = mode.trim() == "block"; whisper_exceptions = ids.split(',').filter_map(|s| s.trim().parse().ok()).collect(); + } else if let Some(rest) = l.strip_prefix("ftlimit ") { + let mut it = rest.split_whitespace().map(|v| v.parse::().unwrap_or(0)); + FT_LIMIT_UP.store(it.next().unwrap_or(0), Ordering::Relaxed); + FT_LIMIT_DOWN.store(it.next().unwrap_or(0), Ordering::Relaxed); } else if l == "unwhisper" { whisper_channels.clear(); whisper_clients.clear(); @@ -3096,6 +3117,7 @@ async fn run(args: Args) -> Result<()> { // Fill the whole chunk (or hit EOF) so every piece but the // last is exactly TRANSFER_CHUNK_BYTES - see its comment. let mut filled = 0; + let started = std::time::Instant::now(); let read = loop { match stream.read(&mut buf[filled..]).await { Ok(0) => break Ok(()), @@ -3121,6 +3143,7 @@ async fn run(args: Args) -> Result<()> { let done = filled < buf.len(); let data = base64::engine::general_purpose::STANDARD.encode(&buf[..filled]); emit(&Event::FileDownloadChunk { cid, path: path.clone(), offset, data, done }); + ft_pace(&FT_LIMIT_DOWN, filled, started).await; if done { return; } @@ -3135,10 +3158,15 @@ async fn run(args: Args) -> Result<()> { let mut stream = result.stream; tokio::spawn(async move { let slice = if seek < data.len() { &data[seek..] } else { &[][..] }; - match stream.write_all(slice).await { - Ok(_) => emit(&Event::FileUploadDone { cid, path }), - Err(e) => emit(&Event::Error { message: format!("Upload failed: {e}") }), + for piece in slice.chunks(TRANSFER_CHUNK_BYTES) { + let started = std::time::Instant::now(); + if let Err(e) = stream.write_all(piece).await { + emit(&Event::Error { message: format!("Upload failed: {e}") }); + return; + } + ft_pace(&FT_LIMIT_UP, piece.len(), started).await; } + emit(&Event::FileUploadDone { cid, path }); }); } } diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 7e540be..87bc53c 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -1010,6 +1010,10 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { await connection?.downloadFile(msg.channelId, msg.path); break; } + case "setTransferLimit": { + connection?.setTransferLimit(msg.up, msg.down); + break; + } case "uploadFile": { await connection?.uploadFile(msg.channelId, msg.path, msg.dataBase64); break; diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index 3e6264e..85f06d4 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -967,6 +967,12 @@ export class Ts3Connection { this.writeLine(`whisperpolicy ${block ? "block" : "allow"};${ids.join(",")}`); } + /** File transfer bandwidth caps in bytes/s, 0 = unlimited. */ + setTransferLimit(up: unknown, down: unknown): void { + const rate = (v: unknown) => Math.max(0, Math.floor(Number(v) || 0)); + this.writeLine(`ftlimit ${rate(up)} ${rate(down)}`); + } + /** Empty channelIds/clientIds clears whisper mode, returning outgoing * voice to the normal current-channel broadcast. */ async setWhisperTargets(channelIds: number[], clientIds: number[]): Promise { diff --git a/web/src/App.css b/web/src/App.css index 9911798..4466451 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -4679,3 +4679,61 @@ .ts-stream-request-block { opacity: 0.65; } + +/* Options -> Download, file transfer window */ +.ts-download-dir { + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; + margin-bottom: 6px; +} +.ts-download-number { + width: 5em; + margin: 0 4px; +} +.ts-transfers-window { + position: fixed; + right: 16px; + bottom: 48px; + width: min(560px, calc(100vw - 32px)); + max-height: 50vh; + z-index: 1100; + display: flex; + flex-direction: column; +} +.ts-transfers-window .ts-dialog-body { + overflow: auto; +} +.ts-transfers-table { + width: 100%; + border-collapse: collapse; + font-size: 0.9em; +} +.ts-transfers-table td { + padding: 2px 4px; + white-space: nowrap; +} +.ts-transfers-name { + max-width: 180px; + overflow: hidden; + text-overflow: ellipsis; +} +.ts-transfers-table progress { + width: 100px; +} +.ts-transfer-error td { + color: var(--log-error); +} +.ts-transfer-toast { + position: fixed; + right: 16px; + bottom: 16px; + z-index: 1200; + padding: 8px 12px; + background: var(--bg-toolbar-1); + color: var(--text); + border: 1px solid var(--border); + border-radius: 4px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3); +} diff --git a/web/src/App.tsx b/web/src/App.tsx index eb6b074..ca5e4f2 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -151,6 +151,19 @@ import { type IconPack, } from "./iconpack"; import { StillImg } from "./lib/still"; +import { + DEFAULT_DOWNLOAD_SETTINGS, + canPickFolder, + clearDownloadDir, + loadDownloadDir, + loadDownloadSettings, + pickDownloadDir, + resolveSaveTarget, + saveDownloadSettings, + writeToTarget, + type DownloadSettings, + type SaveTarget, +} from "./downloads"; import { GREENTEASPEAK_THEME_ID, GreenteaSpeakChrome, @@ -688,6 +701,10 @@ const DisplayPrefsContext = createContext<{ saveIconPacks: (packs: IconPack[]) => void; whisper: WhisperSettings; setWhisper: (next: WhisperSettings) => void; + downloads: DownloadSettings; + setDownloads: (next: DownloadSettings) => void; + downloadDir: FileSystemDirectoryHandle | null; + setDownloadDir: (dir: FileSystemDirectoryHandle | null) => void; }>({ tree: DEFAULT_TREE_OPTIONS, setTree: () => {}, @@ -697,6 +714,10 @@ const DisplayPrefsContext = createContext<{ saveIconPacks: () => {}, whisper: DEFAULT_WHISPER_SETTINGS, setWhisper: () => {}, + downloads: DEFAULT_DOWNLOAD_SETTINGS, + setDownloads: () => {}, + downloadDir: null, + setDownloadDir: () => {}, }); const DISCONNECT_MESSAGE_KEY = "webspeak3:disconnect-message"; const COLLECTED_URLS_KEY = "webspeak3:collected-urls"; @@ -985,10 +1006,82 @@ function formatRate(bytesPerSec: number): string { * into an actual browser download, without ever round-tripping through the * gateway's HTTP surface - it's all-in-memory via a Blob + object URL. */ function triggerBrowserDownload(filename: string, base64Data: string): void { + downloadBlob(base64Blob(base64Data), filename); +} + +function base64Blob(base64Data: string): Blob { const binary = atob(base64Data); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); - downloadBlob(new Blob([bytes]), filename); + return new Blob([bytes]); +} + +/** One entry of the file transfer window (Options -> Download queue/limits). */ +interface Transfer { + id: number; + dir: "up" | "down"; + cid: number; + path: string; + name: string; + size: number; + done: number; + status: "queued" | "running" | "done" | "error"; + /** Downloads: picked at click time. */ + target?: SaveTarget; + /** Uploads. */ + file?: File; +} + +function FileTransfersWindow({ + transfers, + onClearFinished, + onClose, +}: { + transfers: Transfer[]; + onClearFinished: () => void; + onClose: () => void; +}) { + const t = useT(); + return ( +
+
+ {t("transfers.title")} + +
+
+ {transfers.length === 0 ? ( +

{t("transfers.empty")}

+ ) : ( + + + {transfers.map((x) => ( + + + + + + + + ))} + +
{x.dir === "down" ? "⬇" : "⬆"} + {x.name} + + + + {formatBytes(x.done)} / {formatBytes(x.size)} + {t(`transfers.status.${x.status}`)}
+ )} +
+
+
+ +
+
+
+ ); } function downloadBlob(blob: Blob, filename: string) { @@ -6174,6 +6267,107 @@ function WhisperPanel({ onOpenWhisperLists }: { onOpenWhisperLists: () => void } ); } +function DownloadsPanel() { + const t = useT(); + const { downloads, setDownloads, downloadDir, setDownloadDir } = useContext(DisplayPrefsContext); + const set = (patch: Partial) => setDownloads({ ...downloads, ...patch }); + const limitRow = (key: "uploadLimit" | "downloadLimit") => ( +
+ {t(`downloadSettings.${key}`)} + + +
+ ); + const countRow = (key: "maxUploads" | "maxDownloads") => ( +
+ {t(`downloadSettings.${key}`)} + +
+ ); + return ( + <> +

{t("options.section.downloads")}

+

{t("downloadSettings.subtitle")}

+
+
+ {t("downloadSettings.directory")} +
+ {t("downloadSettings.directoryLabel")} {downloadDir?.name ?? t("downloadSettings.browserDefault")} + + {downloadDir && ( + + )} +
+ + + {!canPickFolder &&

{t("downloadSettings.unsupported")}

} +
+
+ {t("downloadSettings.interface")} + {(["showWindowOnStart", "closeWindowWhenDone", "popupWhenDone"] as const).map((key) => ( + + ))} +
+
+
+ {limitRow("uploadLimit")} + {countRow("maxUploads")} +
+
+ {limitRow("downloadLimit")} + {countRow("maxDownloads")} +
+
+
+ + ); +} + function DesignPanel({ designSelection, onSelectionChange, @@ -7203,6 +7397,8 @@ function OptionsDialog({ ) : active.id === "whispern" ? ( + ) : active.id === "downloads" ? ( + ) : ( <>

{t(`options.section.${active.id}`)}

@@ -7684,6 +7880,13 @@ function AppInner() { const [iconPacks, setIconPacks] = useState(loadIconPacks); const [iconPackId, setIconPackId] = useState(loadSelectedIconPack); const [whisperSettings, setWhisperSettings] = useState(loadWhisperSettings); + const [downloadSettings, setDownloadSettings] = useState(loadDownloadSettings); + const downloadSettingsRef = useRef(downloadSettings); + downloadSettingsRef.current = downloadSettings; + const [downloadDir, setDownloadDir] = useState(null); + useEffect(() => { + void loadDownloadDir().then(setDownloadDir); + }, []); const whisperSettingsRef = useRef(whisperSettings); whisperSettingsRef.current = whisperSettings; const displayPrefs = useMemo( @@ -7708,8 +7911,15 @@ function AppInner() { setWhisperSettings(next); localStorage.setItem(WHISPER_SETTINGS_KEY, JSON.stringify(next)); }, + downloads: downloadSettings, + setDownloads: (next: DownloadSettings) => { + setDownloadSettings(next); + saveDownloadSettings(next); + }, + downloadDir, + setDownloadDir, }), - [treeOptions, iconPacks, iconPackId, whisperSettings] + [treeOptions, iconPacks, iconPackId, whisperSettings, downloadSettings, downloadDir] ); const iconPackStyle = iconPackCss(iconPacks.find((p) => p.id === iconPackId)); const [micOn, setMicOn] = useState(false); @@ -8513,6 +8723,11 @@ function AppInner() { const pieces = downloadChunks.get(key); if (!pieces) return; pieces.push(data.data); + const transfer = findTransfer("down", data.cid, data.path); + if (transfer) { + transfer.done = data.offset + (data.data.length * 3) / 4; + commitTransfers(); + } if (!data.done) return; downloadChunks.delete(key); data = { type: "fileDownloadData", cid: data.cid, path: data.path, data: pieces.join("") }; @@ -8821,8 +9036,15 @@ function AppInner() { })); break; } - case "error": + case "error": { logClient("error", "Connection", data.message); + // ponytail: connector errors carry no transfer id, so the oldest running + // transfer of that kind takes the blame. Add an id when that misfires. + const msg = String(data.message); + const kind = /^download/i.test(msg) ? "down" : /^upload/i.test(msg) ? "up" : /^file transfer/i.test(msg) ? "any" : null; + const failed = + kind && transfersRef.current.find((x) => x.status === "running" && (kind === "any" || x.dir === kind)); + if (failed) finishTransfer(failed, false); if (hasConnectedRef.current) { appendLog({ text: data.message, kind: "error" }); } else { @@ -8831,6 +9053,7 @@ function AppInner() { updateTabMeta(sessionId, { connecting: false, connected: false }); } break; + } case "clientConnectionInfo": setClientConnectionInfo({ clientId: data.clientId, @@ -8912,14 +9135,26 @@ function AppInner() { setServerIconImages((prev) => ({ ...prev, [data.path]: data.data })); } else { const filename = data.path.split("/").filter(Boolean).pop() ?? "download"; - triggerBrowserDownload(filename, data.data); + const transfer = findTransfer("down", data.cid, data.path); + if (!transfer) { + triggerBrowserDownload(filename, data.data); + break; + } + const blob = base64Blob(data.data); + void writeToTarget(transfer.target ?? null, blob).then((saved) => { + if (!saved) downloadBlob(blob, filename); + finishTransfer(transfer, true); + }); } break; } - case "fileUploadDone": + case "fileUploadDone": { + const transfer = findTransfer("up", data.cid, data.path); + if (transfer) finishTransfer(transfer, true); if (data.cid === 0) handleServerIconsRefresh(); else handleFileBrowserRefresh(); break; + } case "permList": setPermissionsEditorEntries(data.entries); break; @@ -10803,15 +11038,92 @@ function AppInner() { window.setTimeout(handleFileBrowserRefresh, 300); }; - const handleFileBrowserDownload = (entry: FileListEntry) => { + // Options -> Download: queue, limits and the transfer window. transfersRef is + // the source of truth because socket handlers keep old closures; the state + // copy only drives re-renders. + const transfersRef = useRef([]); + const [transfers, setTransfers] = useState([]); + const [transfersOpen, setTransfersOpen] = useState(false); + const [transferToast, setTransferToast] = useState<{ name: string } | null>(null); + const nextTransferIdRef = useRef(1); + const commitTransfers = () => setTransfers([...transfersRef.current]); + + const enqueueTransfer = (x: Omit) => { + transfersRef.current.push({ ...x, id: nextTransferIdRef.current++, done: 0, status: "queued" }); + if (downloadSettings.showWindowOnStart) setTransfersOpen(true); + commitTransfers(); + }; + + const findTransfer = (dir: Transfer["dir"], cid: number, path: string) => + transfersRef.current.find((x) => x.status === "running" && x.dir === dir && x.cid === cid && x.path === path); + + const finishTransfer = (x: Transfer, ok: boolean) => { + x.status = ok ? "done" : "error"; + if (ok) x.done = x.size; + const settings = downloadSettingsRef.current; + if (ok && settings.popupWhenDone) setTransferToast({ name: x.name }); + if (settings.closeWindowWhenDone && transfersRef.current.every((y) => y.status === "done")) setTransfersOpen(false); + commitTransfers(); + }; + + // Start queued transfers while under the "Gleichzeitige Uploads/Downloads" caps. + useEffect(() => { + let started = false; + for (const dir of ["down", "up"] as const) { + const max = dir === "down" ? downloadSettings.maxDownloads : downloadSettings.maxUploads; + let running = transfersRef.current.filter((x) => x.dir === dir && x.status === "running").length; + for (const x of transfersRef.current) { + if (running >= max) break; + if (x.dir !== dir || x.status !== "queued") continue; + x.status = "running"; + running++; + started = true; + if (dir === "down") + socketRef.current?.send(JSON.stringify({ type: "downloadFile", channelId: x.cid, path: x.path })); + else void sendUpload(x.cid, x.path, x.file!, x); + } + } + if (started) commitTransfers(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [transfers, downloadSettings.maxDownloads, downloadSettings.maxUploads]); + + useEffect(() => { + if (!transferToast) return; + const id = window.setTimeout(() => setTransferToast(null), 4000); + return () => window.clearTimeout(id); + }, [transferToast]); + + // Bandwidth caps are enforced by the connector; resend for every new connection. + const sentTransferLimitRef = useRef<{ socket: WebSocket | DemoSocket | null; payload: string }>({ + socket: null, + payload: "", + }); + useEffect(() => { + const socket = socketRef.current; + if (!connected || !socket) return; + const payload = JSON.stringify({ + type: "setTransferLimit", + up: downloadSettings.uploadLimit * 1024, + down: downloadSettings.downloadLimit * 1024, + }); + const sent = sentTransferLimitRef.current; + if (sent.socket === socket && sent.payload === payload) return; + socket.send(payload); + sentTransferLimitRef.current = { socket, payload }; + }, [connected, activeSessionId, downloadSettings.uploadLimit, downloadSettings.downloadLimit]); + + const handleFileBrowserDownload = async (entry: FileListEntry) => { if (!fileBrowserTarget) return; - socketRef.current?.send( - JSON.stringify({ - type: "downloadFile", - channelId: fileBrowserTarget.channelId, - path: ftJoinPath(fileBrowserPath, entry.name), - }) - ); + const target = await resolveSaveTarget(downloadSettings, downloadDir, entry.name); + if (target === "cancelled") return; + enqueueTransfer({ + dir: "down", + cid: fileBrowserTarget.channelId, + path: ftJoinPath(fileBrowserPath, entry.name), + name: entry.name, + size: entry.size, + target, + }); }; // The connector refuses anything bigger. Gateways without "chunkedUpload" @@ -10825,13 +11137,20 @@ function AppInner() { const handleFileBrowserUpload = (file: File) => { if (!fileBrowserTarget) return; if (rejectOversizedUpload(file)) return; - void sendUpload(fileBrowserTarget.channelId, ftJoinPath(fileBrowserPath, file.name), file); + enqueueTransfer({ + dir: "up", + cid: fileBrowserTarget.channelId, + path: ftJoinPath(fileBrowserPath, file.name), + name: file.name, + size: file.size, + file, + }); }; // Small pieces keep the gateway from holding a whole file (several times // over) in memory. 192 KiB is a multiple of 3, so each piece base64-encodes // on its own without padding. - const sendUpload = async (channelId: number, path: string, file: File) => { + const sendUpload = async (channelId: number, path: string, file: File, transfer?: Transfer) => { const socket = socketRef.current; if (!gatewayFeatures.has("chunkedUpload")) { socket?.send(JSON.stringify({ type: "uploadFile", channelId, path, dataBase64: await readBase64(file) })); @@ -10842,6 +11161,10 @@ function AppInner() { for (let offset = 0; offset === 0 || offset < file.size; offset += chunkBytes) { const data = await readBase64(file.slice(offset, offset + chunkBytes)); socket?.send(JSON.stringify({ type: "uploadFileChunk", channelId, path, offset, total: file.size, data })); + if (transfer) { + transfer.done = Math.min(file.size, offset + chunkBytes); + commitTransfers(); + } } }; @@ -11337,6 +11660,16 @@ function AppInner() { 🧑‍🤝‍🧑 {t("menu.extras.inviteFriend")} +