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.
This commit is contained in:
Moepchi committed 2026-08-05 22:39:35 +02:00
1 parent 41ac845fbc
commit 7901aafbb1
7 files changed
+862 -4

No files matched your search

+219 -2
View File
@@ -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<PermissionOverviewEntry> },
/// Reply to a "ftlist" request - one channel/path's directory listing.
#[serde(rename = "fileList")]
FileList { cid: u64, path: String, entries: Vec<FileListEntry> },
/// 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<Vec<(u32, i32, bool, bool)>> = 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<FileListEntry> = 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<u16, (u64, String)> = HashMap::new();
let mut pending_uploads: HashMap<u16, (u64, String, Vec<u8>)> = HashMap::new();
enum LoopOutcome {
StdinLine(std::io::Result<Option<String>>),
@@ -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::<u64>() {
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::<u64>() {
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::<u64>() {
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::<u64>() {
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::<u64>() {
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::<u64>(),
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)) => {
+24
View File
@@ -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;
+48 -2
View File
@@ -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<void> {
const sanitized = (path || "/").replace(/[\r\n]+/g, " ").trim() || "/";
this.child?.stdin.write(`ftlist ${channelId} ${sanitized}\n`);
}
async createDirectory(channelId: number, dirname: string): Promise<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.child?.stdin.write(`chat ${sanitized}\n`);
+41
View File
@@ -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);
+403
View File
@@ -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")}
>
<ChannelIcon />
@@ -520,6 +549,7 @@ function ChannelTree({
onOpenPrivateChat={onOpenPrivateChat}
onPokeClient={onPokeClient}
onClientContextMenu={onClientContextMenu}
onChannelContextMenu={onChannelContextMenu}
/>
</li>
))}
@@ -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<HTMLInputElement>(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 (
<div className="ts-dialog-backdrop" {...backdrop}>
<div className="ts-dialog ts-file-browser-dialog" onClick={(e) => e.stopPropagation()}>
<div className="ts-dialog-titlebar">
<span>
{t("fileBrowser.title")} - {channelName}
</span>
<button onClick={onClose} title={t("dialog.close")}>
✕
</button>
</div>
<div className="ts-dialog-body">
<div className="ts-file-browser-toolbar">
<button onClick={() => onNavigate(ftParentPath(path))} disabled={path === "/"} title={t("fileBrowser.up")}>
⬆ {t("fileBrowser.up")}
</button>
<span className="ts-file-browser-path">{path}</span>
<button onClick={onRefresh} title={t("fileBrowser.refresh")}>
🔄
</button>
<button onClick={() => setCreatingDir(true)} title={t("fileBrowser.newFolder")}>
🗀 {t("fileBrowser.newFolder")}
</button>
<button onClick={() => fileInputRef.current?.click()} title={t("fileBrowser.upload")}>
⬆️ {t("fileBrowser.upload")}
</button>
<input
ref={fileInputRef}
type="file"
style={{ display: "none" }}
onChange={(e) => {
const file = e.target.files?.[0];
if (file) onUpload(file);
e.target.value = "";
}}
/>
</div>
{creatingDir && (
<form
className="ts-dialog-row"
onSubmit={(e) => {
e.preventDefault();
if (newDirName.trim()) onCreateDir(newDirName.trim());
setNewDirName("");
setCreatingDir(false);
}}
>
<input
autoFocus
value={newDirName}
onChange={(e) => setNewDirName(e.target.value)}
placeholder={t("fileBrowser.folderName")}
/>
<button type="submit">{t("dialog.ok")}</button>
<button type="button" onClick={() => setCreatingDir(false)}>
{t("dialog.cancel")}
</button>
</form>
)}
{!sorted ? (
<div className="ts-connection-info-loading">
{timedOut ? t("connectionInfo.unavailable") : t("connectionInfo.loading")}
</div>
) : sorted.length === 0 ? (
<div className="ts-connection-info-loading">{t("fileBrowser.empty")}</div>
) : (
<div className="ts-permission-overview-scroll">
<table className="ts-ban-list-table">
<thead>
<tr>
<th>{t("fileBrowser.name")}</th>
<th>{t("fileBrowser.size")}</th>
<th>{t("fileBrowser.modified")}</th>
<th />
</tr>
</thead>
<tbody>
{sorted.map((entry) => (
<tr key={entry.name}>
<td>
{renaming?.entry.name === entry.name ? (
<form
onSubmit={(e) => {
e.preventDefault();
if (renaming.value.trim()) onRename(entry, renaming.value.trim());
setRenaming(null);
}}
>
<input
autoFocus
value={renaming.value}
onChange={(ev) => setRenaming({ entry, value: ev.target.value })}
onBlur={() => setRenaming(null)}
/>
</form>
) : entry.isFile ? (
<span>📄 {entry.name}</span>
) : (
<button
className="ts-link-button"
onClick={() => onNavigate(ftJoinPath(path, entry.name))}
>
📁 {entry.name}
</button>
)}
</td>
<td>{entry.isFile ? formatBytes(entry.size) : ""}</td>
<td>{entry.timestamp}</td>
<td className="ts-file-browser-actions">
{entry.isFile && (
<button onClick={() => onDownload(entry)} title={t("fileBrowser.download")}>
⬇
</button>
)}
<button
onClick={() => setRenaming({ entry, value: entry.name })}
title={t("fileBrowser.rename")}
>
✏
</button>
<button onClick={() => onDelete(entry)} title={t("fileBrowser.delete")}>
🗑
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
<div className="ts-dialog-buttons">
<div />
<div className="ts-dialog-buttons-right">
<button onClick={onClose}>{t("dialog.close")}</button>
</div>
</div>
</div>
</div>
);
}
function PermissionOverviewDialog({
entries,
onClose,
@@ -3192,6 +3423,11 @@ function AppInner() {
} | null>(null);
const [permissionOverviewOpen, setPermissionOverviewOpen] = useState(false);
const [permissionOverview, setPermissionOverview] = useState<PermissionOverviewEntry[] | null>(null);
const [fileBrowserTarget, setFileBrowserTarget] = useState<{ channelId: number; channelName: string } | null>(
null
);
const [fileBrowserPath, setFileBrowserPath] = useState("/");
const [fileBrowserEntries, setFileBrowserEntries] = useState<FileListEntry[] | null>(null);
const [treeWidth, setTreeWidth] = useState(260);
const [upperHeight, setUpperHeight] = useState(340);
const [selected, setSelected] = useState<SelectedItem | null>(null);
@@ -3224,6 +3460,13 @@ function AppInner() {
const clientContextMenuRef = useRef<HTMLDivElement>(null);
const [serverContextMenu, setServerContextMenu] = useState<{ x: number; y: number } | null>(null);
const serverContextMenuRef = useRef<HTMLDivElement>(null);
const [channelContextMenu, setChannelContextMenu] = useState<{
x: number;
y: number;
channelId: number;
channelName: string;
} | null>(null);
const channelContextMenuRef = useRef<HTMLDivElement>(null);
const [whisperChannelIds, setWhisperChannelIds] = useState<Set<number>>(new Set());
const [whisperClientIds, setWhisperClientIds] = useState<Set<number>>(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 && (
<FileBrowserDialog
channelName={fileBrowserTarget.channelName}
path={fileBrowserPath}
entries={fileBrowserEntries}
onNavigate={handleFileBrowserNavigate}
onCreateDir={handleFileBrowserCreateDir}
onDelete={handleFileBrowserDelete}
onRename={handleFileBrowserRename}
onDownload={handleFileBrowserDownload}
onUpload={handleFileBrowserUpload}
onRefresh={handleFileBrowserRefresh}
onClose={() => setFileBrowserTarget(null)}
/>
)}
{contactsOpen && (
<ContactsDialog
contacts={contacts}
@@ -5833,6 +6215,26 @@ function AppInner() {
</div>
)}
{channelContextMenu && (
<div
ref={channelContextMenuRef}
className="ts-context-menu"
style={{ top: channelContextMenu.y, left: channelContextMenu.x }}
>
<div className="ts-context-menu-title">{channelContextMenu.channelName}</div>
<button
className="ts-menu-item"
onClick={() => {
handleShowFileBrowser(channelContextMenu.channelId, channelContextMenu.channelName);
setChannelContextMenu(null);
}}
>
<span className="ts-menu-item-icon">📁</span>
<span className="ts-menu-item-label">{t("channelContext.files")}</span>
</button>
</div>
)}
<div className="ts-body">
<div className="ts-upper" style={{ height: upperHeight }}>
<div className="ts-tree-panel" style={{ width: treeWidth }}>
@@ -5858,6 +6260,7 @@ function AppInner() {
onOpenPrivateChat={handleOpenPrivateChat}
onPokeClient={handlePokeClient}
onClientContextMenu={handleClientContextMenu}
onChannelContextMenu={handleChannelContextMenu}
/>
</>
) : (
+89
View File
@@ -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 "<channelId>:<path>" - a tiny in-memory filesystem so the
* channel file browser has something real to navigate/mutate in the demo. */
const DEMO_FILES: Record<string, DemoFileEntry[]> = {
"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.
+38
View File
@@ -411,6 +411,25 @@ const translations: Record<Lang, Record<string, string>> = {
"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<Lang, Record<string, string>> = {
"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",