From 7901aafbb1b99ce0a6a4d7efdf7cf1f034040761 Mon Sep 17 00:00:00 2001 From: Moepchi Date: Wed, 5 Aug 2026 22:39:35 +0200 Subject: [PATCH] Add file transfer support (#83) Channel-scoped file browser reachable via right-click on a channel: navigate directories, create folders, rename/delete, and upload/download files. Backed by tsclientlib's built-in download_file/upload_file (which already handles the ftinitdownload/ftinitupload -> TCP data-port dance), plus raw ftgetfilelist/ftcreatedir/ftdeletefile/ftrenamefile commands for everything else. Downloads/uploads are buffered whole in memory and base64-relayed over the existing stdin/WebSocket text protocol - fine for a channel filebase's typical file sizes, not meant for huge transfers. Verified against the real server: upload/list/download round-trip reaches the server correctly (list succeeds, upload correctly surfaces the guest account's missing permission via the new FiletransferFailed handling instead of hanging or crashing). Demo mode gets a small in-memory per-channel filesystem so the file browser is fully interactive in the GitHub Pages demo too. --- connector/src/main.rs | 221 ++++++++++++++++++- gateway/src/index.ts | 24 ++ gateway/src/ts3/connection.ts | 50 ++++- web/src/App.css | 41 ++++ web/src/App.tsx | 403 ++++++++++++++++++++++++++++++++++ web/src/demoMode.ts | 89 ++++++++ web/src/i18n.tsx | 38 ++++ 7 files changed, 862 insertions(+), 4 deletions(-) diff --git a/connector/src/main.rs b/connector/src/main.rs index f02df57..87c9a8c 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -8,11 +8,14 @@ use base64::Engine; use clap::Parser; use futures::prelude::*; use serde::{Deserialize, Serialize}; -use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use tsclientlib::audio::AudioHandler; use tsclientlib::events::{Event as BookEvent, PropertyId, PropertyValue}; -use tsclientlib::messages::c2s::{OutClientPokeRequestPart, OutSendTextMessagePart}; +use tsclientlib::messages::c2s::{ + OutClientPokeRequestPart, OutCreateDirectoryPart, OutDeleteFilePart, OutFileListRequestPart, + OutRenameFilePart, OutSendTextMessagePart, +}; use tsclientlib::prelude::*; use tsclientlib::{ data, ChannelId, ClientId, CodecEncryptionMode, Connection, DisconnectOptions, HostBannerMode, @@ -270,6 +273,18 @@ enum Event { /// "permissionlist" lookup. #[serde(rename = "permissionOverview")] PermissionOverview { entries: Vec }, + /// Reply to a "ftlist" request - one channel/path's directory listing. + #[serde(rename = "fileList")] + FileList { cid: u64, path: String, entries: Vec }, + /// A requested file download finished; `data` is the full file content, + /// base64-encoded. Whole files are buffered in memory and sent as one + /// event rather than streamed incrementally - fine for the file sizes a + /// TS3 channel filebase realistically holds, not meant for huge transfers. + #[serde(rename = "fileDownloadData")] + FileDownloadData { cid: u64, path: String, data: String }, + /// A requested file upload finished successfully. + #[serde(rename = "fileUploadDone")] + FileUploadDone { cid: u64, path: String }, } #[derive(Serialize)] @@ -325,6 +340,16 @@ struct GroupEntry { name: String, } +#[derive(Serialize, Clone)] +#[serde(rename_all = "camelCase")] +struct FileListEntry { + path: String, + name: String, + size: u64, + is_file: bool, + timestamp: String, +} + fn emit(event: &Event) { println!("{}", serde_json::to_string(event).unwrap()); } @@ -658,6 +683,18 @@ async fn run(args: Args) -> Result<()> { // Raw permoverview entries received before the permission-name cache was // ready get buffered here and re-emitted once the names arrive. let mut pending_perm_overview_raw: Option> = None; + // Set by "ftlist" while a directory listing is in flight - the server + // replies with one notifyfilelist packet per entry (buffered here), then a + // final notifyfilelistfinished that triggers the actual emit. + let mut pending_file_list: Option<(u64, String)> = None; + let mut file_list_buffer: Vec = Vec::new(); + // client_filetransfer_id -> (cid, path) for in-flight downloads, and + // -> (cid, path, data) for in-flight uploads. tsclientlib resolves the + // ftinitdownload/ftinitupload reply into a ready TCP stream on its own + // (StreamItem::FileDownload/FileUpload below); these just remember which + // request that stream belongs to. + let mut pending_downloads: HashMap = HashMap::new(); + let mut pending_uploads: HashMap)> = HashMap::new(); enum LoopOutcome { StdinLine(std::io::Result>), @@ -1347,6 +1384,130 @@ async fn run(args: Args) -> Result<()> { Err(e) => emit(&Event::Error { message: e.to_string() }), } } + } else if let Some(rest) = l.strip_prefix("ftlist ") { + let mut parts = rest.trim().splitn(2, ' '); + let cid_str = parts.next().unwrap_or(""); + let path = parts.next().unwrap_or("/").trim(); + let path = if path.is_empty() { "/" } else { path }; + match cid_str.parse::() { + Ok(cid) => { + let part = OutFileListRequestPart { + channel_id: ChannelId(cid), + channel_password: Cow::Borrowed(""), + path: Cow::Borrowed(path), + }; + match part.send_with_result(&mut con) { + Ok(handle) => { + pending_file_list = Some((cid, path.to_string())); + file_list_buffer.clear(); + pending_messages.insert(handle, "File list".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + } + } + Err(_) => emit(&Event::Error { message: format!("Invalid channel id: {cid_str}") }), + } + } else if let Some(rest) = l.strip_prefix("ftmkdir ") { + let mut parts = rest.trim().splitn(2, ' '); + let cid_str = parts.next().unwrap_or(""); + let dirname = parts.next().unwrap_or("").trim(); + match cid_str.parse::() { + Ok(cid) => { + let part = OutCreateDirectoryPart { + channel_id: ChannelId(cid), + channel_password: Cow::Borrowed(""), + directory_name: Cow::Borrowed(dirname), + }; + match part.send_with_result(&mut con) { + Ok(handle) => { + pending_messages.insert(handle, "Create directory".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + } + } + Err(_) => emit(&Event::Error { message: format!("Invalid channel id: {cid_str}") }), + } + } else if let Some(rest) = l.strip_prefix("ftdelete ") { + let mut parts = rest.trim().splitn(2, ' '); + let cid_str = parts.next().unwrap_or(""); + let name = parts.next().unwrap_or("").trim(); + match cid_str.parse::() { + Ok(cid) => { + let part = OutDeleteFilePart { + channel_id: ChannelId(cid), + channel_password: Cow::Borrowed(""), + name: Cow::Borrowed(name), + }; + match part.send_with_result(&mut con) { + Ok(handle) => { + pending_messages.insert(handle, "Delete file".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + } + } + Err(_) => emit(&Event::Error { message: format!("Invalid channel id: {cid_str}") }), + } + } else if let Some(rest) = l.strip_prefix("ftrename ") { + let mut parts = rest.splitn(3, '\t'); + let cid_str = parts.next().unwrap_or(""); + let old_name = parts.next().unwrap_or(""); + let new_name = parts.next().unwrap_or(""); + match cid_str.trim().parse::() { + Ok(cid) => { + let part = OutRenameFilePart { + channel_id: ChannelId(cid), + channel_password: Cow::Borrowed(""), + target_channel_id: None, + target_channel_password: None, + old_name: Cow::Borrowed(old_name), + new_name: Cow::Borrowed(new_name), + }; + match part.send_with_result(&mut con) { + Ok(handle) => { + pending_messages.insert(handle, "Rename file".into()); + } + Err(e) => emit(&Event::Error { message: e.to_string() }), + } + } + Err(_) => emit(&Event::Error { message: format!("Invalid ftrename args: {rest}") }), + } + } else if let Some(rest) = l.strip_prefix("ftdownload ") { + // Download uses tsclientlib's own `download_file`/StreamItem::FileDownload + // machinery rather than a raw OutCommand: it already handles the whole + // "ftinitdownload, then connect+auth the returned TCP data port" dance + // for us (see StreamItem::FileDownload handling below). + let mut parts = rest.trim().splitn(2, ' '); + let cid_str = parts.next().unwrap_or(""); + let path = parts.next().unwrap_or("").trim(); + match cid_str.parse::() { + Ok(cid) => match con.download_file(ChannelId(cid), path, None, None) { + Ok(handle) => { + pending_downloads.insert(handle.0, (cid, path.to_string())); + } + Err(e) => emit(&Event::Error { message: format!("Download failed: {e}") }), + }, + Err(_) => emit(&Event::Error { message: format!("Invalid channel id: {cid_str}") }), + } + } else if let Some(rest) = l.strip_prefix("ftupload ") { + let mut parts = rest.splitn(3, '\t'); + let cid_str = parts.next().unwrap_or(""); + let path = parts.next().unwrap_or(""); + let data_b64 = parts.next().unwrap_or(""); + match ( + cid_str.trim().parse::(), + base64::engine::general_purpose::STANDARD.decode(data_b64.trim()), + ) { + (Ok(cid), Ok(bytes)) => { + let size = bytes.len() as u64; + match con.upload_file(ChannelId(cid), path, None, size, true, false) { + Ok(handle) => { + pending_uploads.insert(handle.0, (cid, path.to_string(), bytes)); + } + Err(e) => emit(&Event::Error { message: format!("Upload failed: {e}") }), + } + } + _ => emit(&Event::Error { message: "Invalid ftupload args".into() }), + } } else if let Some(b64) = l.strip_prefix("audio ") { match base64::engine::general_purpose::STANDARD.decode(b64.trim()) { Ok(bytes) => { @@ -1678,6 +1839,62 @@ async fn run(args: Args) -> Result<()> { } } } + if pending_file_list.is_some() { + if let InMessage::FileList(list) = &msg { + for part in list.iter() { + file_list_buffer.push(FileListEntry { + path: part.path.clone(), + name: part.name.clone(), + size: part.size, + is_file: part.is_file, + timestamp: part.date_time.to_string(), + }); + } + } else if let InMessage::FileListFinished(_) = &msg { + if let Some((cid, path)) = pending_file_list.take() { + emit(&Event::FileList { cid, path, entries: std::mem::take(&mut file_list_buffer) }); + } + } + } + } + Some(Ok(StreamItem::FileDownload(handle, result))) => { + if let Some((cid, path)) = pending_downloads.remove(&handle.0) { + // The whole download happens off the main select loop so a big + // 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 + // from a spawned task even while the main loop is emitting too. + let mut stream = result.stream; + tokio::spawn(async move { + let mut buf = Vec::new(); + match stream.read_to_end(&mut buf).await { + Ok(_) => { + let data = base64::engine::general_purpose::STANDARD.encode(&buf); + emit(&Event::FileDownloadData { cid, path, data }); + } + Err(e) => emit(&Event::Error { message: format!("Download failed: {e}") }), + } + }); + } + } + Some(Ok(StreamItem::FileUpload(handle, result))) => { + if let Some((cid, path, data)) = pending_uploads.remove(&handle.0) { + let seek = result.seek_position as usize; + 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}") }), + } + }); + } + } + Some(Ok(StreamItem::FiletransferFailed(handle, e))) => { + let was_pending = pending_downloads.remove(&handle.0).is_some() + || pending_uploads.remove(&handle.0).is_some(); + if was_pending { + emit(&Event::Error { message: format!("File transfer failed: {e}") }); + } } Some(Ok(_)) => {} Some(Err(e)) => { diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 27008ba..5ea932f 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -222,6 +222,30 @@ wss.on("connection", (socket: WebSocket) => { await connection?.getPermissionOverview(); break; } + case "getFileList": { + await connection?.getFileList(msg.channelId, msg.path); + break; + } + case "createDirectory": { + await connection?.createDirectory(msg.channelId, msg.dirname); + break; + } + case "deleteFile": { + await connection?.deleteFile(msg.channelId, msg.name); + break; + } + case "renameFile": { + await connection?.renameFile(msg.channelId, msg.oldName, msg.newName); + break; + } + case "downloadFile": { + await connection?.downloadFile(msg.channelId, msg.path); + break; + } + case "uploadFile": { + await connection?.uploadFile(msg.channelId, msg.path, msg.dataBase64); + break; + } case "disconnect": { await connection?.disconnect(msg.message ?? ""); break; diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index b165b97..abfdf2f 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -81,6 +81,14 @@ export interface OfflineMessageListEntry { isRead: boolean; } +export interface FileListEntry { + path: string; + name: string; + size: number; + isFile: boolean; + timestamp: string; +} + export type ServerLogEntry = | { kind: "clientJoin"; client: string; channel: string } | { kind: "clientLeave"; client: string } @@ -151,7 +159,10 @@ export type Ts3ConnectionEvent = } | { type: "channelGroupList"; entries: GroupEntry[] } | { type: "serverGroupList"; entries: GroupEntry[] } - | { type: "permissionOverview"; entries: PermissionOverviewEntry[] }; + | { type: "permissionOverview"; entries: PermissionOverviewEntry[] } + | { type: "fileList"; cid: number; path: string; entries: FileListEntry[] } + | { type: "fileDownloadData"; cid: number; path: string; data: string } + | { type: "fileUploadDone"; cid: number; path: string }; export interface Ts3ConnectOptions { host: string; @@ -320,7 +331,10 @@ export class Ts3Connection { | { type: "permissionOverview"; entries: { name: string; description: string; value: number; negated: boolean; skip: boolean }[]; - }; + } + | { type: "fileList"; cid: number; path: string; entries: FileListEntry[] } + | { type: "fileDownloadData"; cid: number; path: string; data: string } + | { type: "fileUploadDone"; cid: number; path: string }; if (event.type === "connected") { this.emit({ @@ -596,6 +610,38 @@ export class Ts3Connection { this.child?.stdin.write(`permoverview\n`); } + async getFileList(channelId: number, path: string): Promise { + const sanitized = (path || "/").replace(/[\r\n]+/g, " ").trim() || "/"; + this.child?.stdin.write(`ftlist ${channelId} ${sanitized}\n`); + } + + async createDirectory(channelId: number, dirname: string): Promise { + const sanitized = dirname.replace(/[\r\n]+/g, " ").trim(); + if (sanitized) this.child?.stdin.write(`ftmkdir ${channelId} ${sanitized}\n`); + } + + async deleteFile(channelId: number, name: string): Promise { + const sanitized = name.replace(/[\r\n]+/g, " ").trim(); + if (sanitized) this.child?.stdin.write(`ftdelete ${channelId} ${sanitized}\n`); + } + + async renameFile(channelId: number, oldName: string, newName: string): Promise { + const sanitize = (s: string) => s.replace(/[\r\n\t]+/g, " ").trim(); + this.child?.stdin.write(`ftrename ${channelId}\t${sanitize(oldName)}\t${sanitize(newName)}\n`); + } + + async downloadFile(channelId: number, path: string): Promise { + const sanitized = path.replace(/[\r\n]+/g, " ").trim(); + if (sanitized) this.child?.stdin.write(`ftdownload ${channelId} ${sanitized}\n`); + } + + /** `dataBase64` is the raw file content, base64-encoded - the browser reads + * the picked File as a data URL/ArrayBuffer and sends it up already encoded. */ + async uploadFile(channelId: number, path: string, dataBase64: string): Promise { + const sanitizedPath = path.replace(/[\r\n\t]+/g, " ").trim(); + this.child?.stdin.write(`ftupload ${channelId}\t${sanitizedPath}\t${dataBase64}\n`); + } + async sendChatMessage(message: string): Promise { const sanitized = message.replace(/[\r\n]+/g, " ").trim(); if (sanitized) this.child?.stdin.write(`chat ${sanitized}\n`); diff --git a/web/src/App.css b/web/src/App.css index 8ed24f3..fc23446 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -1157,6 +1157,47 @@ overflow-y: auto; } +.ts-file-browser-dialog { + width: 680px; +} + +.ts-file-browser-toolbar { + display: flex; + align-items: center; + gap: 0.4rem; + margin-bottom: 0.5rem; + flex-wrap: wrap; +} + +.ts-file-browser-path { + flex: 1; + font-family: monospace; + color: var(--text-muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ts-file-browser-actions { + display: flex; + gap: 0.25rem; + justify-content: flex-end; +} + +.ts-link-button { + background: none; + border: none; + color: var(--accent, #4a9eff); + cursor: pointer; + padding: 0; + font: inherit; + text-align: left; +} + +.ts-link-button:hover { + text-decoration: underline; +} + .ts-server-protocol-log-line { padding: 0.15rem 0.4rem; border-bottom: 1px solid var(--border-soft); diff --git a/web/src/App.tsx b/web/src/App.tsx index c7facf7..a7ff78e 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -328,6 +328,14 @@ interface PermissionOverviewEntry { skip: boolean; } +interface FileListEntry { + path: string; + name: string; + size: number; + isFile: boolean; + timestamp: string; +} + interface ClientConnectionInfoData { clientId: number; pingMs: number | null; @@ -364,6 +372,24 @@ function formatBytes(bytes: number): string { return `${value.toFixed(1)} ${units[unitIndex]}`; } +/** Turns a base64-encoded file (as delivered by the "fileDownloadData" event) + * 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 { + const binary = atob(base64Data); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + const blob = new Blob([bytes]); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); +} + function formatDurationSecs(totalSeconds: number): string { const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); @@ -439,6 +465,7 @@ function ChannelTree({ onOpenPrivateChat, onPokeClient, onClientContextMenu, + onChannelContextMenu, }: { channels: ChannelInfo[]; clients: ClientInfo[]; @@ -451,6 +478,7 @@ function ChannelTree({ onOpenPrivateChat: (clientId: number, clientName: string) => void; onPokeClient: (clientId: number, clientName: string) => void; onClientContextMenu: (e: React.MouseEvent, clientId: number, clientName: string, isSelf: boolean) => void; + onChannelContextMenu: (e: React.MouseEvent, channelId: number, channelName: string) => void; }) { const t = useT(); const children = channels.filter((c) => c.parent === parent).sort((a, b) => a.order - b.order); @@ -466,6 +494,7 @@ function ChannelTree({ }`} onClick={() => onSelectItem({ type: "channel", id: channel.id })} onDoubleClick={() => onSwitchChannel(channel.id)} + onContextMenu={(e) => onChannelContextMenu(e, channel.id, channel.name)} title={t("tree.clickToSelect")} > @@ -520,6 +549,7 @@ function ChannelTree({ onOpenPrivateChat={onOpenPrivateChat} onPokeClient={onPokeClient} onClientContextMenu={onClientContextMenu} + onChannelContextMenu={onChannelContextMenu} /> ))} @@ -1616,6 +1646,207 @@ function GroupAssignDialog({ ); } +/** Builds the full channel-relative path TS3's ft* commands expect (e.g. + * "/foo/bar.txt") from a directory and a bare entry name. */ +function ftJoinPath(dir: string, name: string): string { + const base = dir === "/" || dir === "" ? "" : dir.replace(/\/+$/, ""); + return `${base}/${name}`; +} + +function ftParentPath(dir: string): string { + if (dir === "/" || dir === "") return "/"; + const trimmed = dir.replace(/\/+$/, ""); + const idx = trimmed.lastIndexOf("/"); + return idx <= 0 ? "/" : trimmed.slice(0, idx); +} + +function FileBrowserDialog({ + channelName, + path, + entries, + onNavigate, + onCreateDir, + onDelete, + onRename, + onDownload, + onUpload, + onRefresh, + onClose, +}: { + channelName: string; + path: string; + entries: FileListEntry[] | null; + onNavigate: (path: string) => void; + onCreateDir: (name: string) => void; + onDelete: (entry: FileListEntry) => void; + onRename: (entry: FileListEntry, newName: string) => void; + onDownload: (entry: FileListEntry) => void; + onUpload: (file: File) => void; + onRefresh: () => void; + onClose: () => void; +}) { + const t = useT(); + const backdrop = useBackdropDismiss(onClose); + const [timedOut, setTimedOut] = useState(false); + const [renaming, setRenaming] = useState<{ entry: FileListEntry; value: string } | null>(null); + const [creatingDir, setCreatingDir] = useState(false); + const [newDirName, setNewDirName] = useState(""); + const fileInputRef = useRef(null); + + useEffect(() => { + setTimedOut(false); + if (entries) return; + const id = window.setTimeout(() => setTimedOut(true), 6000); + return () => window.clearTimeout(id); + }, [entries, path]); + + const sorted = + entries + ?.slice() + .sort((a, b) => (a.isFile === b.isFile ? a.name.localeCompare(b.name) : a.isFile ? 1 : -1)) ?? null; + + return ( +
+
e.stopPropagation()}> +
+ + {t("fileBrowser.title")} - {channelName} + + +
+
+
+ + {path} + + + + { + const file = e.target.files?.[0]; + if (file) onUpload(file); + e.target.value = ""; + }} + /> +
+ {creatingDir && ( +
{ + e.preventDefault(); + if (newDirName.trim()) onCreateDir(newDirName.trim()); + setNewDirName(""); + setCreatingDir(false); + }} + > + setNewDirName(e.target.value)} + placeholder={t("fileBrowser.folderName")} + /> + + +
+ )} + {!sorted ? ( +
+ {timedOut ? t("connectionInfo.unavailable") : t("connectionInfo.loading")} +
+ ) : sorted.length === 0 ? ( +
{t("fileBrowser.empty")}
+ ) : ( +
+ + + + + + + + + + {sorted.map((entry) => ( + + + + + + + ))} + +
{t("fileBrowser.name")}{t("fileBrowser.size")}{t("fileBrowser.modified")} +
+ {renaming?.entry.name === entry.name ? ( +
{ + e.preventDefault(); + if (renaming.value.trim()) onRename(entry, renaming.value.trim()); + setRenaming(null); + }} + > + setRenaming({ entry, value: ev.target.value })} + onBlur={() => setRenaming(null)} + /> +
+ ) : entry.isFile ? ( + 📄 {entry.name} + ) : ( + + )} +
{entry.isFile ? formatBytes(entry.size) : ""}{entry.timestamp} + {entry.isFile && ( + + )} + + +
+
+ )} +
+
+
+
+ +
+
+
+
+ ); +} + function PermissionOverviewDialog({ entries, onClose, @@ -3192,6 +3423,11 @@ function AppInner() { } | null>(null); const [permissionOverviewOpen, setPermissionOverviewOpen] = useState(false); const [permissionOverview, setPermissionOverview] = useState(null); + const [fileBrowserTarget, setFileBrowserTarget] = useState<{ channelId: number; channelName: string } | null>( + null + ); + const [fileBrowserPath, setFileBrowserPath] = useState("/"); + const [fileBrowserEntries, setFileBrowserEntries] = useState(null); const [treeWidth, setTreeWidth] = useState(260); const [upperHeight, setUpperHeight] = useState(340); const [selected, setSelected] = useState(null); @@ -3224,6 +3460,13 @@ function AppInner() { const clientContextMenuRef = useRef(null); const [serverContextMenu, setServerContextMenu] = useState<{ x: number; y: number } | null>(null); const serverContextMenuRef = useRef(null); + const [channelContextMenu, setChannelContextMenu] = useState<{ + x: number; + y: number; + channelId: number; + channelName: string; + } | null>(null); + const channelContextMenuRef = useRef(null); const [whisperChannelIds, setWhisperChannelIds] = useState>(new Set()); const [whisperClientIds, setWhisperClientIds] = useState>(new Set()); const [whisperMenuOpen, setWhisperMenuOpen] = useState(false); @@ -3791,6 +4034,17 @@ function AppInner() { case "permissionOverview": setPermissionOverview(data.entries); break; + case "fileList": + setFileBrowserEntries(data.entries); + break; + case "fileDownloadData": { + const filename = data.path.split("/").filter(Boolean).pop() ?? "download"; + triggerBrowserDownload(filename, data.data); + break; + } + case "fileUploadDone": + handleFileBrowserRefresh(); + break; } }; @@ -3969,6 +4223,22 @@ function AppInner() { }; }, [serverContextMenu]); + useEffect(() => { + if (!channelContextMenu) return; + const onPointerDown = (e: MouseEvent) => { + if (!channelContextMenuRef.current?.contains(e.target as Node)) setChannelContextMenu(null); + }; + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === "Escape") setChannelContextMenu(null); + }; + window.addEventListener("mousedown", onPointerDown); + window.addEventListener("keydown", onKeyDown); + return () => { + window.removeEventListener("mousedown", onPointerDown); + window.removeEventListener("keydown", onKeyDown); + }; + }, [channelContextMenu]); + useEffect(() => { if (!connected) { setWhisperChannelIds(new Set()); @@ -4545,6 +4815,102 @@ function AppInner() { socketRef.current?.send(JSON.stringify({ type: "getPermissionOverview" })); }; + const handleChannelContextMenu = (e: React.MouseEvent, channelId: number, channelName: string) => { + e.preventDefault(); + const x = Math.min(e.clientX, window.innerWidth - 220); + const y = Math.min(e.clientY, window.innerHeight - 200); + setChannelContextMenu({ x, y, channelId, channelName }); + }; + + const handleShowFileBrowser = (channelId: number, channelName: string) => { + setFileBrowserTarget({ channelId, channelName }); + setFileBrowserPath("/"); + setFileBrowserEntries(null); + socketRef.current?.send(JSON.stringify({ type: "getFileList", channelId, path: "/" })); + }; + + const handleFileBrowserNavigate = (path: string) => { + if (!fileBrowserTarget) return; + setFileBrowserPath(path); + setFileBrowserEntries(null); + socketRef.current?.send(JSON.stringify({ type: "getFileList", channelId: fileBrowserTarget.channelId, path })); + }; + + const handleFileBrowserRefresh = () => { + if (!fileBrowserTarget) return; + setFileBrowserEntries(null); + socketRef.current?.send( + JSON.stringify({ type: "getFileList", channelId: fileBrowserTarget.channelId, path: fileBrowserPath }) + ); + }; + + const handleFileBrowserCreateDir = (name: string) => { + if (!fileBrowserTarget) return; + socketRef.current?.send( + JSON.stringify({ + type: "createDirectory", + channelId: fileBrowserTarget.channelId, + dirname: ftJoinPath(fileBrowserPath, name), + }) + ); + // ftcreatedir gets no dedicated reply - the server processes commands from + // one connection in order, so a refresh sent right after is guaranteed to + // see the new directory. + window.setTimeout(handleFileBrowserRefresh, 300); + }; + + const handleFileBrowserDelete = (entry: FileListEntry) => { + if (!fileBrowserTarget) return; + if (!window.confirm(t("fileBrowser.deleteConfirm"))) return; + socketRef.current?.send( + JSON.stringify({ + type: "deleteFile", + channelId: fileBrowserTarget.channelId, + name: ftJoinPath(fileBrowserPath, entry.name), + }) + ); + window.setTimeout(handleFileBrowserRefresh, 300); + }; + + const handleFileBrowserRename = (entry: FileListEntry, newName: string) => { + if (!fileBrowserTarget) return; + socketRef.current?.send( + JSON.stringify({ + type: "renameFile", + channelId: fileBrowserTarget.channelId, + oldName: ftJoinPath(fileBrowserPath, entry.name), + newName: ftJoinPath(fileBrowserPath, newName), + }) + ); + window.setTimeout(handleFileBrowserRefresh, 300); + }; + + const handleFileBrowserDownload = (entry: FileListEntry) => { + if (!fileBrowserTarget) return; + socketRef.current?.send( + JSON.stringify({ + type: "downloadFile", + channelId: fileBrowserTarget.channelId, + path: ftJoinPath(fileBrowserPath, entry.name), + }) + ); + }; + + const handleFileBrowserUpload = (file: File) => { + if (!fileBrowserTarget) return; + const channelId = fileBrowserTarget.channelId; + const targetPath = ftJoinPath(fileBrowserPath, file.name); + const reader = new FileReader(); + reader.onload = () => { + const result = reader.result as string; // data:*/*;base64,AAAA... + const base64 = result.slice(result.indexOf(",") + 1); + socketRef.current?.send( + JSON.stringify({ type: "uploadFile", channelId, path: targetPath, dataBase64: base64 }) + ); + }; + reader.readAsDataURL(file); + }; + const handleSendPoke = () => { if (!pokeTarget) return; socketRef.current?.send( @@ -5389,6 +5755,22 @@ function AppInner() { /> )} + {fileBrowserTarget && ( + setFileBrowserTarget(null)} + /> + )} + {contactsOpen && ( )} + {channelContextMenu && ( +
+
{channelContextMenu.channelName}
+ +
+ )} +
@@ -5858,6 +6260,7 @@ function AppInner() { onOpenPrivateChat={handleOpenPrivateChat} onPokeClient={handlePokeClient} onClientContextMenu={handleClientContextMenu} + onChannelContextMenu={handleChannelContextMenu} /> ) : ( diff --git a/web/src/demoMode.ts b/web/src/demoMode.ts index 541e2fd..0ebd494 100644 --- a/web/src/demoMode.ts +++ b/web/src/demoMode.ts @@ -62,6 +62,36 @@ const DEMO_NPCS: DemoClient[] = [ { id: 105, channel: 3, name: "Riley", inputMuted: false, outputMuted: false, inputHardwareEnabled: true, away: true, awayMessage: "brb, grabbing coffee", isChannelCommander: false, country: "DE", uid: "demo-uid-riley", databaseId: 5, channelGroup: 4, serverGroups: [3, 4] }, ]; +interface DemoFileEntry { + path: string; + name: string; + size: number; + isFile: boolean; + timestamp: string; +} + +/** Keyed by ":" - a tiny in-memory filesystem so the + * channel file browser has something real to navigate/mutate in the demo. */ +const DEMO_FILES: Record = { + "1:/": [ + { path: "/", name: "readme.txt", size: 182, isFile: true, timestamp: "2024-01-01 12:00:00" }, + { path: "/", name: "Musik", size: 0, isFile: false, timestamp: "2024-01-01 12:00:00" }, + ], + "1:/Musik": [ + { path: "/Musik", name: "lobby-theme.mp3", size: 4 * 1024 * 1024, isFile: true, timestamp: "2024-01-02 09:30:00" }, + ], + "2:/": [], + "3:/": [], +}; + +function demoFileKey(channelId: number, path: string): string { + return `${channelId}:${path}`; +} + +function demoNowTimestamp(): string { + return new Date().toISOString().slice(0, 19).replace("T", " "); +} + const SELF_ID = 101; /** @@ -384,6 +414,65 @@ export class DemoSocket { ); break; } + case "getFileList": { + const key = demoFileKey(msg.channelId, msg.path); + this.after(300, () => + this.emit({ type: "fileList", cid: msg.channelId, path: msg.path, entries: DEMO_FILES[key] ?? [] }) + ); + break; + } + case "createDirectory": { + const dir = msg.dirname as string; + const parent = dir.slice(0, dir.lastIndexOf("/")) || "/"; + const name = dir.slice(dir.lastIndexOf("/") + 1); + const parentKey = demoFileKey(msg.channelId, parent); + DEMO_FILES[parentKey] = (DEMO_FILES[parentKey] ?? []).filter((e) => e.name !== name); + DEMO_FILES[parentKey].push({ path: parent, name, size: 0, isFile: false, timestamp: demoNowTimestamp() }); + DEMO_FILES[demoFileKey(msg.channelId, dir)] = []; + break; + } + case "deleteFile": { + const full = msg.name as string; + const parent = full.slice(0, full.lastIndexOf("/")) || "/"; + const name = full.slice(full.lastIndexOf("/") + 1); + const parentKey = demoFileKey(msg.channelId, parent); + if (DEMO_FILES[parentKey]) DEMO_FILES[parentKey] = DEMO_FILES[parentKey].filter((e) => e.name !== name); + break; + } + case "renameFile": { + const oldFull = msg.oldName as string; + const newFull = msg.newName as string; + const parent = oldFull.slice(0, oldFull.lastIndexOf("/")) || "/"; + const oldName = oldFull.slice(oldFull.lastIndexOf("/") + 1); + const newName = newFull.slice(newFull.lastIndexOf("/") + 1); + const entry = DEMO_FILES[demoFileKey(msg.channelId, parent)]?.find((e) => e.name === oldName); + if (entry) entry.name = newName; + break; + } + case "downloadFile": { + const full = msg.path as string; + const name = full.slice(full.lastIndexOf("/") + 1); + this.after(400, () => + this.emit({ + type: "fileDownloadData", + cid: msg.channelId, + path: full, + data: btoa(`This is a demo file. There is no real content behind "${name}" in WebSpeak3's demo mode.`), + }) + ); + break; + } + case "uploadFile": { + const full = msg.path as string; + const parent = full.slice(0, full.lastIndexOf("/")) || "/"; + const name = full.slice(full.lastIndexOf("/") + 1); + const parentKey = demoFileKey(msg.channelId, parent); + const sizeBytes = Math.floor(((msg.dataBase64 as string).length * 3) / 4); + DEMO_FILES[parentKey] = (DEMO_FILES[parentKey] ?? []).filter((e) => e.name !== name); + DEMO_FILES[parentKey].push({ path: parent, name, size: sizeBytes, isFile: true, timestamp: demoNowTimestamp() }); + this.after(400, () => this.emit({ type: "fileUploadDone", cid: msg.channelId, path: full })); + break; + } // "disconnect" is intentionally unhandled here: handleDisconnect() in // App.tsx always calls socket.close() right after sending it, and // close() already emits the "disconnected" event below. diff --git a/web/src/i18n.tsx b/web/src/i18n.tsx index fcacf54..0cf5034 100644 --- a/web/src/i18n.tsx +++ b/web/src/i18n.tsx @@ -411,6 +411,25 @@ const translations: Record> = { "permissionOverview.negated": "Negiert", "permissionOverview.skip": "Skip", + "dialog.ok": "OK", + "channelContext.files": "Dateien...", + "fileBrowser.title": "Dateitransfers", + "fileBrowser.up": "Nach oben", + "fileBrowser.refresh": "Aktualisieren", + "fileBrowser.newFolder": "Neuer Ordner", + "fileBrowser.upload": "Hochladen", + "fileBrowser.folderName": "Ordnername", + "fileBrowser.empty": "Dieser Ordner ist leer.", + "fileBrowser.name": "Name", + "fileBrowser.size": "Größe", + "fileBrowser.modified": "Geändert", + "fileBrowser.download": "Herunterladen", + "fileBrowser.rename": "Umbenennen", + "fileBrowser.delete": "Löschen", + "fileBrowser.deleteConfirm": "Wirklich löschen?", + "fileBrowser.uploading": "Wird hochgeladen...", + "fileBrowser.downloading": "Wird heruntergeladen...", + "clientContext.privateChat": "Privater Chat", "clientContext.poke": "Anstupsen", "clientContext.copyName": "Namen kopieren", @@ -864,6 +883,25 @@ const translations: Record> = { "permissionOverview.negated": "Negated", "permissionOverview.skip": "Skip", + "dialog.ok": "OK", + "channelContext.files": "Files...", + "fileBrowser.title": "File Transfers", + "fileBrowser.up": "Up", + "fileBrowser.refresh": "Refresh", + "fileBrowser.newFolder": "New Folder", + "fileBrowser.upload": "Upload", + "fileBrowser.folderName": "Folder name", + "fileBrowser.empty": "This folder is empty.", + "fileBrowser.name": "Name", + "fileBrowser.size": "Size", + "fileBrowser.modified": "Modified", + "fileBrowser.download": "Download", + "fileBrowser.rename": "Rename", + "fileBrowser.delete": "Delete", + "fileBrowser.deleteConfirm": "Really delete?", + "fileBrowser.uploading": "Uploading...", + "fileBrowser.downloading": "Downloading...", + "clientContext.privateChat": "Private chat", "clientContext.poke": "Poke", "clientContext.copyName": "Copy name",