mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-03 09:52:50 +08:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e7add6dc8 | ||
|
|
983ce1e105 | ||
|
|
7d14c3409e | ||
|
|
882265beae |
No files matched your search
@@ -47,16 +47,23 @@ def xrpc(method: str, payload: dict | bytes, token: str | None = None, content_t
|
|||||||
return json.load(res)
|
return json.load(res)
|
||||||
|
|
||||||
|
|
||||||
def fetch(url: str, retries: int = 2) -> tuple[bytes, str]:
|
def fetch(url: str, attempt: int = 1) -> tuple[bytes, str]:
|
||||||
req = urllib.request.Request(url, headers={"User-Agent": "webspeak3-release-announcer"})
|
req = urllib.request.Request(url, headers={"User-Agent": "webspeak3-release-announcer"})
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(req, timeout=30) as res:
|
with urllib.request.urlopen(req, timeout=30) as res:
|
||||||
return res.read(), res.headers.get_content_type()
|
return res.read(), res.headers.get_content_type()
|
||||||
except urllib.error.HTTPError as err:
|
except urllib.error.HTTPError as err:
|
||||||
if err.code != 429 or not retries: # GitHub's image service throttles bursts now and then
|
# GitHub's image service throttles right after a release, often for over a minute.
|
||||||
|
# 15+30+45+60 s stays well inside the job's 5-minute timeout.
|
||||||
|
if err.code != 429 or attempt > 4:
|
||||||
raise
|
raise
|
||||||
time.sleep(10)
|
wait = 15 * attempt
|
||||||
return fetch(url, retries - 1)
|
retry_after = err.headers.get("Retry-After", "")
|
||||||
|
if retry_after.isdigit():
|
||||||
|
wait = min(int(retry_after), 60)
|
||||||
|
print(f"Preview image throttled (429), retrying in {wait} s.")
|
||||||
|
time.sleep(wait)
|
||||||
|
return fetch(url, attempt + 1)
|
||||||
|
|
||||||
|
|
||||||
def link_card(release: dict, text: str) -> dict:
|
def link_card(release: dict, text: str) -> dict:
|
||||||
|
|||||||
+151
-18
@@ -37,6 +37,16 @@ use tsproto_packets::packets::{AudioData, CodecType, Direction, Flags, OutAudio,
|
|||||||
const FRAME_SAMPLES: usize = 960;
|
const FRAME_SAMPLES: usize = 960;
|
||||||
/// Upper bound for a file download relayed to the browser (see its use).
|
/// Upper bound for a file download relayed to the browser (see its use).
|
||||||
const MAX_DOWNLOAD_BYTES: u64 = 25 << 20;
|
const MAX_DOWNLOAD_BYTES: u64 = 25 << 20;
|
||||||
|
/// Uploads are capped the same way, independent of what the browser checks.
|
||||||
|
const MAX_UPLOAD_BYTES: u64 = 24 << 20;
|
||||||
|
/// File transfers cross the gateway in pieces of this size (raw bytes, a
|
||||||
|
/// multiple of 3 so the base64 pieces can simply be concatenated). One huge
|
||||||
|
/// 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;
|
||||||
|
/// Half-received chunked uploads per connection - each can hold up to
|
||||||
|
/// MAX_UPLOAD_BYTES until it completes.
|
||||||
|
const MAX_PARTIAL_UPLOADS: usize = 4;
|
||||||
const MAX_ICON_BYTES: u64 = 512 << 10;
|
const MAX_ICON_BYTES: u64 = 512 << 10;
|
||||||
/// Avatars are fetched for everyone in the user's channel without asking;
|
/// Avatars are fetched for everyone in the user's channel without asking;
|
||||||
/// TS3 servers default to a 300 KiB avatar size limit.
|
/// TS3 servers default to a 300 KiB avatar size limit.
|
||||||
@@ -385,12 +395,11 @@ enum Event {
|
|||||||
/// Reply to a "ftlist" request - one channel/path's directory listing.
|
/// Reply to a "ftlist" request - one channel/path's directory listing.
|
||||||
#[serde(rename = "fileList")]
|
#[serde(rename = "fileList")]
|
||||||
FileList { cid: u64, path: String, entries: Vec<FileListEntry> },
|
FileList { cid: u64, path: String, entries: Vec<FileListEntry> },
|
||||||
/// A requested file download finished; `data` is the full file content,
|
/// One piece of a requested file download, base64-encoded. `offset` is
|
||||||
/// base64-encoded. Whole files are buffered in memory and sent as one
|
/// the raw byte offset of this piece (0 starts a new download), `done`
|
||||||
/// event rather than streamed incrementally - fine for the file sizes a
|
/// marks the last one. Pieces arrive in order.
|
||||||
/// TS3 channel filebase realistically holds, not meant for huge transfers.
|
#[serde(rename = "fileDownloadChunk")]
|
||||||
#[serde(rename = "fileDownloadData")]
|
FileDownloadChunk { cid: u64, path: String, offset: u64, data: String, done: bool },
|
||||||
FileDownloadData { cid: u64, path: String, data: String },
|
|
||||||
/// A requested file upload finished successfully.
|
/// A requested file upload finished successfully.
|
||||||
#[serde(rename = "fileUploadDone")]
|
#[serde(rename = "fileUploadDone")]
|
||||||
FileUploadDone { cid: u64, path: String },
|
FileUploadDone { cid: u64, path: String },
|
||||||
@@ -489,6 +498,54 @@ struct FileListEntry {
|
|||||||
timestamp: String,
|
timestamp: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Handles one `ftuploadchunk <cid>\t<offset>\t<total>\t<path>\t<base64>`
|
||||||
|
/// line. Pieces come in order; offset 0 starts an upload. Returns the complete
|
||||||
|
/// file once the piece that reaches <total> has arrived.
|
||||||
|
fn take_upload_chunk(
|
||||||
|
partials: &mut HashMap<(u64, String), (u64, Vec<u8>)>,
|
||||||
|
rest: &str,
|
||||||
|
) -> Result<Option<(u64, String, Vec<u8>)>, String> {
|
||||||
|
let mut parts: Vec<&str> = rest.splitn(5, '\t').collect();
|
||||||
|
// The stdin loop trims each line, which eats the trailing tab of an empty piece.
|
||||||
|
if parts.len() == 4 {
|
||||||
|
parts.push("");
|
||||||
|
}
|
||||||
|
let [cid, offset, total, path, data] = parts.as_slice() else {
|
||||||
|
return Err("Invalid ftuploadchunk args".into());
|
||||||
|
};
|
||||||
|
let (Ok(cid), Ok(offset), Ok(total), Ok(bytes)) = (
|
||||||
|
cid.trim().parse::<u64>(),
|
||||||
|
offset.trim().parse::<u64>(),
|
||||||
|
total.trim().parse::<u64>(),
|
||||||
|
base64::engine::general_purpose::STANDARD.decode(data.trim()),
|
||||||
|
) else {
|
||||||
|
return Err("Invalid ftuploadchunk args".into());
|
||||||
|
};
|
||||||
|
let key = (cid, path.to_string());
|
||||||
|
if offset == 0 {
|
||||||
|
if total > MAX_UPLOAD_BYTES {
|
||||||
|
return Err(format!("Upload refused: {path} is larger than {} KiB", MAX_UPLOAD_BYTES >> 10));
|
||||||
|
}
|
||||||
|
if !partials.contains_key(&key) && partials.len() >= MAX_PARTIAL_UPLOADS {
|
||||||
|
return Err("Too many uploads at once".into());
|
||||||
|
}
|
||||||
|
partials.insert(key.clone(), (total, Vec::with_capacity(total as usize)));
|
||||||
|
}
|
||||||
|
let Some((expected, buf)) = partials.get_mut(&key) else {
|
||||||
|
return Err(format!("Upload failed: {path} has no upload in progress"));
|
||||||
|
};
|
||||||
|
if buf.len() as u64 != offset || *expected != total || offset + bytes.len() as u64 > total {
|
||||||
|
partials.remove(&key);
|
||||||
|
return Err(format!("Upload failed: {path} arrived out of order"));
|
||||||
|
}
|
||||||
|
buf.extend_from_slice(&bytes);
|
||||||
|
if (buf.len() as u64) < total {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let (_, bytes) = partials.remove(&key).expect("present, checked above");
|
||||||
|
Ok(Some((cid, key.1, bytes)))
|
||||||
|
}
|
||||||
|
|
||||||
fn emit(event: &Event) {
|
fn emit(event: &Event) {
|
||||||
println!("{}", serde_json::to_string(event).unwrap());
|
println!("{}", serde_json::to_string(event).unwrap());
|
||||||
}
|
}
|
||||||
@@ -1056,6 +1113,8 @@ async fn run(args: Args) -> Result<()> {
|
|||||||
// request that stream belongs to.
|
// request that stream belongs to.
|
||||||
let mut pending_downloads: HashMap<u16, (u64, String)> = HashMap::new();
|
let mut pending_downloads: HashMap<u16, (u64, String)> = HashMap::new();
|
||||||
let mut pending_uploads: HashMap<u16, (u64, String, Vec<u8>)> = HashMap::new();
|
let mut pending_uploads: HashMap<u16, (u64, String, Vec<u8>)> = HashMap::new();
|
||||||
|
// Chunked uploads still arriving from the browser: (cid, path) -> (total size, bytes so far).
|
||||||
|
let mut partial_uploads: HashMap<(u64, String), (u64, Vec<u8>)> = HashMap::new();
|
||||||
// Set by "permissionlist" while waiting to emit the full permission
|
// Set by "permissionlist" while waiting to emit the full permission
|
||||||
// catalog (name-resolution reuses the same permission_names cache/fetch
|
// catalog (name-resolution reuses the same permission_names cache/fetch
|
||||||
// as "permoverview" above).
|
// as "permoverview" above).
|
||||||
@@ -1089,6 +1148,10 @@ async fn run(args: Args) -> Result<()> {
|
|||||||
loop {
|
loop {
|
||||||
let mut events = con.events();
|
let mut events = con.events();
|
||||||
let outcome = tokio::select! {
|
let outcome = tokio::select! {
|
||||||
|
// After a stall (e.g. CPU steal) the missed audio ticks fire in a burst.
|
||||||
|
// Polling in order drains the queued packets first, otherwise a tick can
|
||||||
|
// find an empty queue and play Opus loss concealment instead.
|
||||||
|
biased;
|
||||||
line = stdin_lines.next_line() => LoopOutcome::StdinLine(line),
|
line = stdin_lines.next_line() => LoopOutcome::StdinLine(line),
|
||||||
ev = events.next() => LoopOutcome::ConEvent(ev),
|
ev = events.next() => LoopOutcome::ConEvent(ev),
|
||||||
_ = audio_ticker.tick() => LoopOutcome::AudioTick,
|
_ = audio_ticker.tick() => LoopOutcome::AudioTick,
|
||||||
@@ -2178,6 +2241,19 @@ async fn run(args: Args) -> Result<()> {
|
|||||||
}
|
}
|
||||||
_ => emit(&Event::Error { message: "Invalid ftupload args".into() }),
|
_ => emit(&Event::Error { message: "Invalid ftupload args".into() }),
|
||||||
}
|
}
|
||||||
|
} else if let Some(rest) = l.strip_prefix("ftuploadchunk ") {
|
||||||
|
match take_upload_chunk(&mut partial_uploads, rest) {
|
||||||
|
Ok(Some((cid, path, bytes))) => {
|
||||||
|
match con.upload_file(ChannelId(cid), &path, None, bytes.len() as u64, true, false) {
|
||||||
|
Ok(handle) => {
|
||||||
|
pending_uploads.insert(handle.0, (cid, path, bytes));
|
||||||
|
}
|
||||||
|
Err(e) => emit(&Event::Error { message: format!("Upload failed: {e}") }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None) => {}
|
||||||
|
Err(message) => emit(&Event::Error { message }),
|
||||||
|
}
|
||||||
} else if l == "permissionlist" {
|
} else if l == "permissionlist" {
|
||||||
if pending_permission_list {
|
if pending_permission_list {
|
||||||
// A catalog fetch is already in flight (triggered by an
|
// A catalog fetch is already in flight (triggered by an
|
||||||
@@ -2973,9 +3049,9 @@ async fn run(args: Args) -> Result<()> {
|
|||||||
// file does not stall channel switches, chat, etc. while in flight;
|
// file does not stall channel switches, chat, etc. while in flight;
|
||||||
// emit() is just a println! under the hood, so it is safe to call
|
// emit() is just a println! under the hood, so it is safe to call
|
||||||
// from a spawned task even while the main loop is emitting too.
|
// from a spawned task even while the main loop is emitting too.
|
||||||
// Everything is buffered and then sent as one base64 JSON line,
|
// It goes out in TRANSFER_CHUNK_BYTES pieces but the browser
|
||||||
// so cap it - a server could otherwise announce (or just send)
|
// still assembles the whole file, so cap it - a server could
|
||||||
// gigabytes and take the whole gateway host's memory with it.
|
// otherwise announce (or just send) gigabytes.
|
||||||
let stream = result.stream;
|
let stream = result.stream;
|
||||||
let announced_size = result.size;
|
let announced_size = result.size;
|
||||||
// Group/server icons are fetched automatically, without the user
|
// Group/server icons are fetched automatically, without the user
|
||||||
@@ -2992,16 +3068,42 @@ async fn run(args: Args) -> Result<()> {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let mut buf = Vec::new();
|
let mut stream = stream.take(limit + 1);
|
||||||
match stream.take(limit + 1).read_to_end(&mut buf).await {
|
let mut buf = vec![0u8; TRANSFER_CHUNK_BYTES];
|
||||||
Ok(_) if buf.len() as u64 > limit => emit(&Event::Error {
|
let mut offset = 0u64;
|
||||||
message: format!("Download aborted: {path} is larger than {} KiB", limit >> 10),
|
loop {
|
||||||
}),
|
// Fill the whole chunk (or hit EOF) so every piece but the
|
||||||
Ok(_) => {
|
// last is exactly TRANSFER_CHUNK_BYTES - see its comment.
|
||||||
let data = base64::engine::general_purpose::STANDARD.encode(&buf);
|
let mut filled = 0;
|
||||||
emit(&Event::FileDownloadData { cid, path, data });
|
let read = loop {
|
||||||
|
match stream.read(&mut buf[filled..]).await {
|
||||||
|
Ok(0) => break Ok(()),
|
||||||
|
Ok(n) => {
|
||||||
|
filled += n;
|
||||||
|
if filled == buf.len() {
|
||||||
|
break Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => break Err(e),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Err(e) = read {
|
||||||
|
emit(&Event::Error { message: format!("Download failed: {e}") });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
Err(e) => emit(&Event::Error { message: format!("Download failed: {e}") }),
|
if offset + filled as u64 > limit {
|
||||||
|
emit(&Event::Error {
|
||||||
|
message: format!("Download aborted: {path} is larger than {} KiB", limit >> 10),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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 });
|
||||||
|
if done {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
offset += filled as u64;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3083,3 +3185,34 @@ async fn run(args: Args) -> Result<()> {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn chunk(offset: u64, total: u64, data: &[u8]) -> String {
|
||||||
|
format!("7\t{offset}\t{total}\t/a b.txt\t{}", base64::engine::general_purpose::STANDARD.encode(data))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn upload_chunks_assemble_in_order_and_reject_gaps() {
|
||||||
|
let mut partials = HashMap::new();
|
||||||
|
assert_eq!(take_upload_chunk(&mut partials, &chunk(0, 5, b"abc")), Ok(None));
|
||||||
|
assert_eq!(
|
||||||
|
take_upload_chunk(&mut partials, &chunk(3, 5, b"de")),
|
||||||
|
Ok(Some((7, "/a b.txt".to_string(), b"abcde".to_vec())))
|
||||||
|
);
|
||||||
|
assert!(partials.is_empty());
|
||||||
|
|
||||||
|
take_upload_chunk(&mut partials, &chunk(0, 5, b"abc")).unwrap();
|
||||||
|
assert!(take_upload_chunk(&mut partials, &chunk(4, 5, b"e")).is_err());
|
||||||
|
assert!(partials.is_empty(), "a gap drops the upload");
|
||||||
|
assert!(take_upload_chunk(&mut partials, &chunk(0, MAX_UPLOAD_BYTES + 1, b"a")).is_err());
|
||||||
|
|
||||||
|
// An empty file's only piece reaches us with its trailing tab trimmed off.
|
||||||
|
assert_eq!(
|
||||||
|
take_upload_chunk(&mut partials, chunk(0, 0, b"").trim_end()),
|
||||||
|
Ok(Some((7, "/a b.txt".to_string(), Vec::new())))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
-4
@@ -100,9 +100,11 @@ const connectionsPerIp = new Map<string, number>();
|
|||||||
const CONNECT_RATE_LIMIT = Number(process.env.CONNECT_RATE_LIMIT ?? 30);
|
const CONNECT_RATE_LIMIT = Number(process.env.CONNECT_RATE_LIMIT ?? 30);
|
||||||
const isConnectRateLimited = createRateLimiter(CONNECT_RATE_LIMIT, 60_000);
|
const isConnectRateLimited = createRateLimiter(CONNECT_RATE_LIMIT, 60_000);
|
||||||
|
|
||||||
// Largest single WS message: file uploads travel base64-encoded inside one,
|
// Largest single WS message. Uploads now arrive in small "uploadFileChunk"
|
||||||
// so this is ~4/3 of the biggest uploadable file (see MAX_UPLOAD_BYTES in
|
// pieces; this size only stays for browsers still running a client from
|
||||||
// web/src/App.tsx). ws's own default is 100 MiB.
|
// before that, which send the whole file base64-encoded in one "uploadFile"
|
||||||
|
// message (~4/3 of MAX_UPLOAD_BYTES in web/src/App.tsx). ws's own default is
|
||||||
|
// 100 MiB.
|
||||||
const WS_MAX_PAYLOAD = 34 * 1024 * 1024;
|
const WS_MAX_PAYLOAD = 34 * 1024 * 1024;
|
||||||
|
|
||||||
const PORT = Number(process.env.PORT ?? 8080);
|
const PORT = Number(process.env.PORT ?? 8080);
|
||||||
@@ -118,7 +120,7 @@ const WEB_DIST = process.env.WEB_DIST ?? path.resolve(__dirname, "../../web/dist
|
|||||||
const SERVE_STATIC = process.env.WEB_STATIC !== "0";
|
const SERVE_STATIC = process.env.WEB_STATIC !== "0";
|
||||||
|
|
||||||
// Sent to every browser in the "hello" message on socket open; see there.
|
// Sent to every browser in the "hello" message on socket open; see there.
|
||||||
const GATEWAY_FEATURES = ["clientVolume", "keepalive"];
|
const GATEWAY_FEATURES = ["clientVolume", "keepalive", "chunkedUpload"];
|
||||||
|
|
||||||
// Optional TURN relay for screen streams, also handed out in "hello". With
|
// Optional TURN relay for screen streams, also handed out in "hello". With
|
||||||
// TURN_SECRET (coturn's use-auth-secret) every socket gets its own credential,
|
// TURN_SECRET (coturn's use-auth-secret) every socket gets its own credential,
|
||||||
@@ -994,6 +996,10 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
|
|||||||
await connection?.uploadFile(msg.channelId, msg.path, msg.dataBase64);
|
await connection?.uploadFile(msg.channelId, msg.path, msg.dataBase64);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
case "uploadFileChunk": {
|
||||||
|
await connection?.uploadFileChunk(msg.channelId, msg.path, msg.offset, msg.total, msg.data);
|
||||||
|
break;
|
||||||
|
}
|
||||||
case "getPermissionCatalog": {
|
case "getPermissionCatalog": {
|
||||||
await connection?.getPermissionCatalog();
|
await connection?.getPermissionCatalog();
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ export type Ts3ConnectionEvent =
|
|||||||
| { type: "serverGroupList"; entries: GroupEntry[] }
|
| { type: "serverGroupList"; entries: GroupEntry[] }
|
||||||
| { type: "permissionOverview"; entries: PermissionOverviewEntry[] }
|
| { type: "permissionOverview"; entries: PermissionOverviewEntry[] }
|
||||||
| { type: "fileList"; cid: number; path: string; entries: FileListEntry[] }
|
| { type: "fileList"; cid: number; path: string; entries: FileListEntry[] }
|
||||||
| { type: "fileDownloadData"; cid: number; path: string; data: string }
|
| { type: "fileDownloadChunk"; cid: number; path: string; offset: number; data: string; done: boolean }
|
||||||
| { type: "fileUploadDone"; cid: number; path: string }
|
| { type: "fileUploadDone"; cid: number; path: string }
|
||||||
| { type: "permList"; scope: PermScope; id1: number; id2: number | null; entries: PermissionOverviewEntry[] }
|
| { type: "permList"; scope: PermScope; id1: number; id2: number | null; entries: PermissionOverviewEntry[] }
|
||||||
| { type: "permissionCatalog"; entries: PermissionCatalogEntry[] }
|
| { type: "permissionCatalog"; entries: PermissionCatalogEntry[] }
|
||||||
@@ -451,7 +451,7 @@ export class Ts3Connection {
|
|||||||
entries: { name: string; description: string; value: number; negated: boolean; skip: boolean }[];
|
entries: { name: string; description: string; value: number; negated: boolean; skip: boolean }[];
|
||||||
}
|
}
|
||||||
| { type: "fileList"; cid: number; path: string; entries: FileListEntry[] }
|
| { type: "fileList"; cid: number; path: string; entries: FileListEntry[] }
|
||||||
| { type: "fileDownloadData"; cid: number; path: string; data: string }
|
| { type: "fileDownloadChunk"; cid: number; path: string; offset: number; data: string; done: boolean }
|
||||||
| { type: "fileUploadDone"; cid: number; path: string }
|
| { type: "fileUploadDone"; cid: number; path: string }
|
||||||
| { type: "permList"; scope: PermScope; id1: number; id2: number | null; entries: PermissionOverviewEntry[] }
|
| { type: "permList"; scope: PermScope; id1: number; id2: number | null; entries: PermissionOverviewEntry[] }
|
||||||
| { type: "permissionCatalog"; entries: PermissionCatalogEntry[] }
|
| { type: "permissionCatalog"; entries: PermissionCatalogEntry[] }
|
||||||
@@ -824,6 +824,17 @@ export class Ts3Connection {
|
|||||||
this.writeLine(`ftupload ${channelId}\t${sanitizedPath}\t${dataBase64}`);
|
this.writeLine(`ftupload ${channelId}\t${sanitizedPath}\t${dataBase64}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One piece of a chunked upload (see "chunkedUpload" in GATEWAY_FEATURES).
|
||||||
|
* Pieces must arrive in order; offset 0 starts the upload and the piece
|
||||||
|
* that reaches `total` sends it. Keeps every message small, unlike
|
||||||
|
* uploadFile above, which only stays for clients from before the split. */
|
||||||
|
async uploadFileChunk(channelId: number, path: string, offset: number, total: number, dataBase64: string): Promise<void> {
|
||||||
|
if (![channelId, offset, total].every(Number.isSafeInteger)) return;
|
||||||
|
if (typeof dataBase64 !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/.test(dataBase64)) return;
|
||||||
|
const sanitizedPath = path.replace(/[\r\n\t]+/g, " ").trim();
|
||||||
|
this.writeLine(`ftuploadchunk ${channelId}\t${offset}\t${total}\t${sanitizedPath}\t${dataBase64}`);
|
||||||
|
}
|
||||||
|
|
||||||
async sendChatMessage(message: string): Promise<void> {
|
async sendChatMessage(message: string): Promise<void> {
|
||||||
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
|
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
|
||||||
if (sanitized) this.writeLine(`chat ${sanitized}`);
|
if (sanitized) this.writeLine(`chat ${sanitized}`);
|
||||||
|
|||||||
+65
-25
@@ -3806,6 +3806,18 @@ const CUSTOM_ICON_ID_THRESHOLD = 1000;
|
|||||||
// Keep in sync with WS_MAX_PAYLOAD in gateway/src/index.ts (base64 adds ~4/3).
|
// Keep in sync with WS_MAX_PAYLOAD in gateway/src/index.ts (base64 adds ~4/3).
|
||||||
const MAX_UPLOAD_BYTES = 24 * 1024 * 1024;
|
const MAX_UPLOAD_BYTES = 24 * 1024 * 1024;
|
||||||
|
|
||||||
|
function readBase64(blob: Blob): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = () => {
|
||||||
|
const result = reader.result as string; // data:*/*;base64,AAAA...
|
||||||
|
resolve(result.slice(result.indexOf(",") + 1));
|
||||||
|
};
|
||||||
|
reader.onerror = () => reject(reader.error);
|
||||||
|
reader.readAsDataURL(blob);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** Deterministic color for a group's letter badge - same icon id always
|
/** Deterministic color for a group's letter badge - same icon id always
|
||||||
* produces the same hue, so a group looks consistent across the tree
|
* produces the same hue, so a group looks consistent across the tree
|
||||||
* without needing the real (unavailable) TeamSpeak icon graphics. */
|
* without needing the real (unavailable) TeamSpeak icon graphics. */
|
||||||
@@ -7483,8 +7495,23 @@ function AppInner() {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Downloads arrive in pieces (see the connector's TRANSFER_CHUNK_BYTES),
|
||||||
|
// keyed by channel + path; every piece but the last is a whole number of
|
||||||
|
// base64 groups, so the strings just concatenate.
|
||||||
|
const downloadChunks = new Map<string, string[]>();
|
||||||
|
|
||||||
const onmessage = (event: MessageEvent) => {
|
const onmessage = (event: MessageEvent) => {
|
||||||
const data = JSON.parse(event.data);
|
let data = JSON.parse(event.data);
|
||||||
|
if (data.type === "fileDownloadChunk") {
|
||||||
|
const key = `${data.cid}\n${data.path}`;
|
||||||
|
if (data.offset === 0) downloadChunks.set(key, []);
|
||||||
|
const pieces = downloadChunks.get(key);
|
||||||
|
if (!pieces) return;
|
||||||
|
pieces.push(data.data);
|
||||||
|
if (!data.done) return;
|
||||||
|
downloadChunks.delete(key);
|
||||||
|
data = { type: "fileDownloadData", cid: data.cid, path: data.path, data: pieces.join("") };
|
||||||
|
}
|
||||||
|
|
||||||
// Broadcast, not tied to any one session - show it regardless of which
|
// Broadcast, not tied to any one session - show it regardless of which
|
||||||
// tab is active, and regardless of which tab's socket it arrived on
|
// tab is active, and regardless of which tab's socket it arrived on
|
||||||
@@ -7973,14 +8000,17 @@ function AppInner() {
|
|||||||
// detach and run the drop handling right away.
|
// detach and run the drop handling right away.
|
||||||
socket.onmessage = socket.onerror = socket.onclose = null;
|
socket.onmessage = socket.onerror = socket.onclose = null;
|
||||||
socket.close();
|
socket.close();
|
||||||
|
logClient("warning", "Connection", `No keepalive from the gateway for ${KEEPALIVE_TIMEOUT_MS / 1000} s`);
|
||||||
current().onclose();
|
current().onclose();
|
||||||
}, KEEPALIVE_TIMEOUT_MS);
|
}, KEEPALIVE_TIMEOUT_MS);
|
||||||
}
|
}
|
||||||
if (event.data !== KEEPALIVE_MESSAGE) current().onmessage(event);
|
if (event.data !== KEEPALIVE_MESSAGE) current().onmessage(event);
|
||||||
};
|
};
|
||||||
socket.onerror = () => current().onerror();
|
socket.onerror = () => current().onerror();
|
||||||
socket.onclose = () => {
|
socket.onclose = (event) => {
|
||||||
clearTimeout(watchdog);
|
clearTimeout(watchdog);
|
||||||
|
// 1000/1001 are clean closes; 1006 means the link died without a close frame.
|
||||||
|
logClient("info", "Connection", `Gateway connection closed (code ${event.code ?? "?"})`);
|
||||||
current().onclose();
|
current().onclose();
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -8086,7 +8116,7 @@ function AppInner() {
|
|||||||
// network blip, or the page coming back from being backgrounded/suspended
|
// network blip, or the page coming back from being backgrounded/suspended
|
||||||
// — without disturbing which tab is active or losing chat/scroll history.
|
// — without disturbing which tab is active or losing chat/scroll history.
|
||||||
const reconnectSession = (sessionId: string) => {
|
const reconnectSession = (sessionId: string) => {
|
||||||
const params = sessionParamsRef.current.get(sessionId);
|
let params = sessionParamsRef.current.get(sessionId);
|
||||||
const rec = sessionsRef.current.get(sessionId);
|
const rec = sessionsRef.current.get(sessionId);
|
||||||
if (!params || !rec) return;
|
if (!params || !rec) return;
|
||||||
// Already open or mid-(re)connect — nothing to do.
|
// Already open or mid-(re)connect — nothing to do.
|
||||||
@@ -8094,6 +8124,17 @@ function AppInner() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Come back in the channel we were in, like the native client does. Kept
|
||||||
|
// in the params so a failed attempt (empty client list) still aims there.
|
||||||
|
const isActive = sessionId === activeSessionIdRef.current;
|
||||||
|
const state = isActive ? { clients, ownClientId } : rec.parked;
|
||||||
|
const lastChannel = state?.clients.find((c) => c.id === state.ownClientId)?.channel;
|
||||||
|
if (lastChannel) {
|
||||||
|
const cachedPassword = isActive ? channelPasswordCacheRef.current.get(lastChannel) : undefined;
|
||||||
|
params = { ...params, defaultChannel: `/${lastChannel}`, channelPassword: cachedPassword ?? params.channelPassword };
|
||||||
|
sessionParamsRef.current.set(sessionId, params);
|
||||||
|
}
|
||||||
|
|
||||||
logClient("info", "Connection", `Reconnecting to ${params.host}…`);
|
logClient("info", "Connection", `Reconnecting to ${params.host}…`);
|
||||||
const socket = DEMO_MODE ? new DemoSocket() : new WebSocket(GATEWAY_URL);
|
const socket = DEMO_MODE ? new DemoSocket() : new WebSocket(GATEWAY_URL);
|
||||||
rec.socket = socket;
|
rec.socket = socket;
|
||||||
@@ -9693,8 +9734,8 @@ function AppInner() {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Uploads travel base64-encoded in a single WebSocket message; anything
|
// The connector refuses anything bigger. Gateways without "chunkedUpload"
|
||||||
// above the gateway's maxPayload would make it drop the whole connection.
|
// also take the whole file as one WebSocket message, capped by maxPayload.
|
||||||
const rejectOversizedUpload = (file: File): boolean => {
|
const rejectOversizedUpload = (file: File): boolean => {
|
||||||
if (file.size <= MAX_UPLOAD_BYTES) return false;
|
if (file.size <= MAX_UPLOAD_BYTES) return false;
|
||||||
appendLog({ text: t("fileBrowser.tooLarge", { mb: String(MAX_UPLOAD_BYTES >> 20) }), kind: "error" });
|
appendLog({ text: t("fileBrowser.tooLarge", { mb: String(MAX_UPLOAD_BYTES >> 20) }), kind: "error" });
|
||||||
@@ -9704,17 +9745,24 @@ function AppInner() {
|
|||||||
const handleFileBrowserUpload = (file: File) => {
|
const handleFileBrowserUpload = (file: File) => {
|
||||||
if (!fileBrowserTarget) return;
|
if (!fileBrowserTarget) return;
|
||||||
if (rejectOversizedUpload(file)) return;
|
if (rejectOversizedUpload(file)) return;
|
||||||
const channelId = fileBrowserTarget.channelId;
|
void sendUpload(fileBrowserTarget.channelId, ftJoinPath(fileBrowserPath, file.name), file);
|
||||||
const targetPath = ftJoinPath(fileBrowserPath, file.name);
|
};
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onload = () => {
|
// Small pieces keep the gateway from holding a whole file (several times
|
||||||
const result = reader.result as string; // data:*/*;base64,AAAA...
|
// over) in memory. 192 KiB is a multiple of 3, so each piece base64-encodes
|
||||||
const base64 = result.slice(result.indexOf(",") + 1);
|
// on its own without padding.
|
||||||
socketRef.current?.send(
|
const sendUpload = async (channelId: number, path: string, file: File) => {
|
||||||
JSON.stringify({ type: "uploadFile", channelId, path: targetPath, dataBase64: base64 })
|
const socket = socketRef.current;
|
||||||
);
|
if (!gatewayFeatures.has("chunkedUpload")) {
|
||||||
};
|
socket?.send(JSON.stringify({ type: "uploadFile", channelId, path, dataBase64: await readBase64(file) }));
|
||||||
reader.readAsDataURL(file);
|
return;
|
||||||
|
}
|
||||||
|
const chunkBytes = 192 * 1024;
|
||||||
|
// offset === 0 still sends one (empty) piece for an empty file.
|
||||||
|
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 }));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleShowServerIcons = () => {
|
const handleShowServerIcons = () => {
|
||||||
@@ -9733,15 +9781,7 @@ function AppInner() {
|
|||||||
|
|
||||||
const handleServerIconUpload = (iconId: number, file: File) => {
|
const handleServerIconUpload = (iconId: number, file: File) => {
|
||||||
if (rejectOversizedUpload(file)) return;
|
if (rejectOversizedUpload(file)) return;
|
||||||
const reader = new FileReader();
|
void sendUpload(0, `/icon_${iconId}`, file);
|
||||||
reader.onload = () => {
|
|
||||||
const result = reader.result as string;
|
|
||||||
const base64 = result.slice(result.indexOf(",") + 1);
|
|
||||||
socketRef.current?.send(
|
|
||||||
JSON.stringify({ type: "uploadFile", channelId: 0, path: `/icon_${iconId}`, dataBase64: base64 })
|
|
||||||
);
|
|
||||||
};
|
|
||||||
reader.readAsDataURL(file);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleServerIconDelete = (entry: FileListEntry) => {
|
const handleServerIconDelete = (entry: FileListEntry) => {
|
||||||
|
|||||||
Reference in new issue
Block a user