Implement channel file transfers
Add file up/downloads and directory operations for channel file repositories, reachable from a channel's right-click "Browse files". Core (com.ts3client.net.filetransfer): - FileTransferManager drives the TS3 file protocol on the ts3j socket. ftinitupload/ftinitdownload results arrive out-of-band as notifystartupload/notifystartdownload (success) or notifystatusfiletransfer (failure) events, not as command responses, so negotiation correlates them by clientftfid via a CompletableFuture. The byte phase opens a raw TCP socket, sends the ftkey, then streams. - FileTransfer: observable per-transfer handle (state, progress, cancel). - RemoteFile: UI-facing listing DTO, keeping core free of ts3j API types. TeamspeakConnection exposes list/mkdir/delete/rename and up/download and manages the manager's lifecycle. Swing FileBrowserDialog provides the browser UI with a live per-transfer progress strip. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -15,6 +15,9 @@ import com.ts3client.audio.AudioBackend;
|
||||
import com.ts3client.audio.VoiceInput;
|
||||
import com.ts3client.audio.VoiceOutput;
|
||||
import com.ts3client.config.Settings;
|
||||
import com.ts3client.net.filetransfer.FileTransfer;
|
||||
import com.ts3client.net.filetransfer.FileTransferManager;
|
||||
import com.ts3client.net.filetransfer.RemoteFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.InetSocketAddress;
|
||||
@@ -38,10 +41,12 @@ public final class TeamspeakConnection implements TS3Listener {
|
||||
private VoiceInput microphone;
|
||||
private VoiceOutput playback;
|
||||
private LocalIdentity identity;
|
||||
private FileTransferManager fileTransfers;
|
||||
|
||||
private volatile boolean connected;
|
||||
private volatile int selfClientId = -1;
|
||||
private volatile long connectedAtMs;
|
||||
private volatile String serverHost;
|
||||
|
||||
/** Outstanding {@code getconnectioninfo} requests awaiting a server report, keyed by client id. */
|
||||
private final Map<Integer, PendingConnInfo> pendingConnInfo = new ConcurrentHashMap<>();
|
||||
@@ -143,6 +148,8 @@ public final class TeamspeakConnection implements TS3Listener {
|
||||
|
||||
// Protocol connection established; anything past this point is best-effort.
|
||||
selfClientId = client.getClientId();
|
||||
serverHost = address;
|
||||
fileTransfers = new FileTransferManager(client, () -> serverHost);
|
||||
client.setMicrophone(microphone);
|
||||
connected = true;
|
||||
connectedAtMs = System.currentTimeMillis();
|
||||
@@ -235,12 +242,21 @@ public final class TeamspeakConnection implements TS3Listener {
|
||||
VoiceInput mic = microphone;
|
||||
VoiceOutput out = playback;
|
||||
LocalTeamspeakClientSocket sock = client;
|
||||
FileTransferManager ft = fileTransfers;
|
||||
microphone = null;
|
||||
playback = null;
|
||||
client = null;
|
||||
fileTransfers = null;
|
||||
selfClientId = -1;
|
||||
pendingConnInfo.clear();
|
||||
|
||||
if (ft != null) {
|
||||
try {
|
||||
ft.shutdown();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
if (mic != null) {
|
||||
try {
|
||||
mic.stop();
|
||||
@@ -531,6 +547,59 @@ public final class TeamspeakConnection implements TS3Listener {
|
||||
}, "ts3j-clientinfo").start();
|
||||
}
|
||||
|
||||
// ---- file transfers ----
|
||||
|
||||
/** Whether a live connection capable of file transfers is available. */
|
||||
public boolean canTransferFiles() {
|
||||
return connected && fileTransfers != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the files under {@code path} in a channel's repository. Blocking; call
|
||||
* off the UI thread. Throws if not connected or the server denies the request.
|
||||
*/
|
||||
public java.util.List<RemoteFile> listFiles(int channelId, String channelPassword, String path)
|
||||
throws Exception {
|
||||
FileTransferManager ft = fileTransfers;
|
||||
if (ft == null) throw new IllegalStateException("Not connected");
|
||||
return ft.list(channelId, channelPassword, path);
|
||||
}
|
||||
|
||||
public void createDirectory(int channelId, String channelPassword, String dirPath) throws Exception {
|
||||
FileTransferManager ft = fileTransfers;
|
||||
if (ft == null) throw new IllegalStateException("Not connected");
|
||||
ft.createDirectory(channelId, channelPassword, dirPath);
|
||||
}
|
||||
|
||||
public void deleteFile(int channelId, String channelPassword, String fullPath) throws Exception {
|
||||
FileTransferManager ft = fileTransfers;
|
||||
if (ft == null) throw new IllegalStateException("Not connected");
|
||||
ft.delete(channelId, channelPassword, fullPath);
|
||||
}
|
||||
|
||||
public void renameFile(int channelId, String channelPassword, String oldFullPath, String newFullPath)
|
||||
throws Exception {
|
||||
FileTransferManager ft = fileTransfers;
|
||||
if (ft == null) throw new IllegalStateException("Not connected");
|
||||
ft.rename(channelId, channelPassword, oldFullPath, newFullPath);
|
||||
}
|
||||
|
||||
/** Begins downloading a channel file to {@code target}; progress arrives via {@code listener}. */
|
||||
public FileTransfer downloadFile(int channelId, String channelPassword, String remoteFullPath,
|
||||
File target, FileTransfer.Listener listener) {
|
||||
FileTransferManager ft = fileTransfers;
|
||||
if (ft == null) throw new IllegalStateException("Not connected");
|
||||
return ft.download(channelId, channelPassword, remoteFullPath, target, listener);
|
||||
}
|
||||
|
||||
/** Begins uploading {@code source} into a channel; progress arrives via {@code listener}. */
|
||||
public FileTransfer uploadFile(int channelId, String channelPassword, String remoteFullPath,
|
||||
File source, boolean overwrite, FileTransfer.Listener listener) {
|
||||
FileTransferManager ft = fileTransfers;
|
||||
if (ft == null) throw new IllegalStateException("Not connected");
|
||||
return ft.upload(channelId, channelPassword, remoteFullPath, source, overwrite, listener);
|
||||
}
|
||||
|
||||
// ---- connection info ----
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.ts3client.net.filetransfer;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* An observable handle for a single in-flight (or finished) file transfer. Created
|
||||
* by {@link FileTransferManager}; the actual byte copy runs on a background thread
|
||||
* and mutates this object, notifying a {@link Listener} on every change so a UI can
|
||||
* render live progress. All mutating methods are package-private — callers only read.
|
||||
*/
|
||||
public final class FileTransfer {
|
||||
|
||||
public enum Direction {UPLOAD, DOWNLOAD}
|
||||
|
||||
public enum State {
|
||||
/** Announced to the server, file connection not yet established. */
|
||||
PENDING,
|
||||
/** Bytes are actively being transferred. */
|
||||
ACTIVE,
|
||||
COMPLETED,
|
||||
FAILED,
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
/** Notified (off the UI thread) whenever this transfer's progress or state changes. */
|
||||
public interface Listener {
|
||||
void onTransferChanged(FileTransfer transfer);
|
||||
}
|
||||
|
||||
private final Direction direction;
|
||||
private final int channelId;
|
||||
private final String remoteName;
|
||||
private final File localFile;
|
||||
private final Listener listener;
|
||||
|
||||
private volatile long totalBytes;
|
||||
private volatile long transferredBytes;
|
||||
private volatile State state = State.PENDING;
|
||||
private volatile String errorMessage;
|
||||
private volatile boolean cancelRequested;
|
||||
|
||||
private final long startedAtMs = System.currentTimeMillis();
|
||||
private volatile long finishedAtMs;
|
||||
|
||||
FileTransfer(Direction direction, int channelId, String remoteName, File localFile,
|
||||
long totalBytes, Listener listener) {
|
||||
this.direction = direction;
|
||||
this.channelId = channelId;
|
||||
this.remoteName = remoteName;
|
||||
this.localFile = localFile;
|
||||
this.totalBytes = totalBytes;
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
// ---- read-only accessors ----
|
||||
|
||||
public Direction getDirection() {
|
||||
return direction;
|
||||
}
|
||||
|
||||
public int getChannelId() {
|
||||
return channelId;
|
||||
}
|
||||
|
||||
public String getRemoteName() {
|
||||
return remoteName;
|
||||
}
|
||||
|
||||
public File getLocalFile() {
|
||||
return localFile;
|
||||
}
|
||||
|
||||
public long getTotalBytes() {
|
||||
return totalBytes;
|
||||
}
|
||||
|
||||
public long getTransferredBytes() {
|
||||
return transferredBytes;
|
||||
}
|
||||
|
||||
public State getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public boolean isDone() {
|
||||
State s = state;
|
||||
return s == State.COMPLETED || s == State.FAILED || s == State.CANCELLED;
|
||||
}
|
||||
|
||||
/** Completion fraction in [0, 1], or 0 when the total size is unknown. */
|
||||
public double getProgress() {
|
||||
long total = totalBytes;
|
||||
if (total <= 0) return isDone() && state == State.COMPLETED ? 1.0 : 0.0;
|
||||
double p = (double) transferredBytes / total;
|
||||
return p < 0 ? 0 : (p > 1 ? 1 : p);
|
||||
}
|
||||
|
||||
/** Average speed in bytes per second over the transfer's lifetime, or 0 if not measurable. */
|
||||
public double getAverageSpeed() {
|
||||
long end = isDone() ? finishedAtMs : System.currentTimeMillis();
|
||||
long elapsed = Math.max(1, end - startedAtMs);
|
||||
return transferredBytes * 1000.0 / elapsed;
|
||||
}
|
||||
|
||||
/** Requests cancellation; the transfer thread aborts at the next chunk boundary. */
|
||||
public void cancel() {
|
||||
cancelRequested = true;
|
||||
}
|
||||
|
||||
boolean isCancelRequested() {
|
||||
return cancelRequested;
|
||||
}
|
||||
|
||||
// ---- package-private mutators, called by FileTransferManager ----
|
||||
|
||||
void setTotalBytes(long totalBytes) {
|
||||
this.totalBytes = totalBytes;
|
||||
}
|
||||
|
||||
void addTransferred(long delta) {
|
||||
transferredBytes += delta;
|
||||
fireChanged();
|
||||
}
|
||||
|
||||
void markActive() {
|
||||
state = State.ACTIVE;
|
||||
fireChanged();
|
||||
}
|
||||
|
||||
void markCompleted() {
|
||||
finishedAtMs = System.currentTimeMillis();
|
||||
state = State.COMPLETED;
|
||||
fireChanged();
|
||||
}
|
||||
|
||||
void markCancelled() {
|
||||
finishedAtMs = System.currentTimeMillis();
|
||||
state = State.CANCELLED;
|
||||
fireChanged();
|
||||
}
|
||||
|
||||
void markFailed(String message) {
|
||||
finishedAtMs = System.currentTimeMillis();
|
||||
errorMessage = message;
|
||||
state = State.FAILED;
|
||||
fireChanged();
|
||||
}
|
||||
|
||||
private void fireChanged() {
|
||||
if (listener != null) listener.onTransferChanged(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
package com.ts3client.net.filetransfer;
|
||||
|
||||
import com.github.manevolent.ts3j.api.FileTransferParameters;
|
||||
import com.github.manevolent.ts3j.command.SingleCommand;
|
||||
import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter;
|
||||
import com.github.manevolent.ts3j.event.TS3Listener;
|
||||
import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent;
|
||||
import com.github.manevolent.ts3j.protocol.ProtocolRole;
|
||||
import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Implements the TeamSpeak 3 channel file-transfer protocol on top of a connected
|
||||
* {@link LocalTeamspeakClientSocket}.
|
||||
*
|
||||
* <p>Directory operations ({@link #list}, {@link #createDirectory}, {@link #delete},
|
||||
* {@link #rename}) are ordinary control commands and run synchronously on the caller's
|
||||
* thread. Byte transfers ({@link #download}, {@link #upload}) are two-phase: an
|
||||
* {@code ftinit*} control command negotiates a one-time key, host and port, after which
|
||||
* a raw TCP connection to the server's file port carries the bytes. That copy runs on a
|
||||
* background thread and reports through the returned {@link FileTransfer} handle.
|
||||
*/
|
||||
public final class FileTransferManager {
|
||||
|
||||
private static final int CONNECT_TIMEOUT_MS = 15_000;
|
||||
private static final int BUFFER_SIZE = 64 * 1024;
|
||||
/** How long to wait for the server's {@code notifystart*} reply after an {@code ftinit*}. */
|
||||
private static final long NEGOTIATE_TIMEOUT_MS = 15_000;
|
||||
|
||||
/** TeamSpeak error id returned by {@code ftgetfilelist} for an empty directory. */
|
||||
private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501;
|
||||
|
||||
private final LocalTeamspeakClientSocket socket;
|
||||
/** Host we are connected to, used when the server reports no dedicated file-transfer host. */
|
||||
private final Supplier<String> fallbackHost;
|
||||
private final AtomicInteger clientTransferId = new AtomicInteger(1);
|
||||
private final ExecutorService transferPool = Executors.newCachedThreadPool(r -> {
|
||||
Thread t = new Thread(r, "ts3j-filetransfer");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
|
||||
/**
|
||||
* In-flight {@code ftinit*} negotiations keyed by our {@code clientftfid}. The server
|
||||
* answers an init out-of-band with a {@code notifystart*} (success) or a
|
||||
* {@code notifystatusfiletransfer} (failure) event, which {@link #ftEventListener}
|
||||
* routes back to the waiting transfer thread.
|
||||
*/
|
||||
private final Map<Integer, CompletableFuture<Map<String, String>>> pendingInits = new ConcurrentHashMap<>();
|
||||
private final TS3Listener ftEventListener = new TS3Listener() {
|
||||
@Override
|
||||
public void onUnknownEvent(UnknownTeamspeakEvent e) {
|
||||
handleFileTransferEvent(e);
|
||||
}
|
||||
};
|
||||
|
||||
public FileTransferManager(LocalTeamspeakClientSocket socket, Supplier<String> fallbackHost) {
|
||||
this.socket = socket;
|
||||
this.fallbackHost = fallbackHost;
|
||||
socket.addListener(ftEventListener);
|
||||
}
|
||||
|
||||
// ---- directory operations ----
|
||||
|
||||
/**
|
||||
* Lists the files and subdirectories directly under {@code path} in the given
|
||||
* channel's repository. Returns an empty list for an empty directory.
|
||||
*/
|
||||
public List<RemoteFile> list(int channelId, String channelPassword, String path)
|
||||
throws Exception {
|
||||
SingleCommand cmd = new SingleCommand("ftgetfilelist", ProtocolRole.CLIENT,
|
||||
new CommandSingleParameter("cid", Integer.toString(channelId)),
|
||||
new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword),
|
||||
new CommandSingleParameter("path", path == null || path.isEmpty() ? "/" : path));
|
||||
|
||||
List<RemoteFile> files = new ArrayList<>();
|
||||
Iterable<SingleCommand> rows;
|
||||
try {
|
||||
rows = socket.executeCommand(cmd).get();
|
||||
} catch (com.github.manevolent.ts3j.command.CommandException e) {
|
||||
if (e.getErrorId() == ERROR_DATABASE_EMPTY_RESULT) return files;
|
||||
throw e;
|
||||
}
|
||||
for (SingleCommand row : rows) {
|
||||
Map<String, String> m = row.toMap();
|
||||
String name = m.get("name");
|
||||
if (name == null || name.isEmpty()) continue;
|
||||
files.add(new RemoteFile(
|
||||
name,
|
||||
m.getOrDefault("path", path),
|
||||
parseLong(m.get("size")),
|
||||
"0".equals(m.get("type")),
|
||||
parseLong(m.get("datetime"))));
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/** Creates a new directory at {@code dirPath} (a full path such as {@code /new}). */
|
||||
public void createDirectory(int channelId, String channelPassword, String dirPath)
|
||||
throws Exception {
|
||||
SingleCommand cmd = new SingleCommand("ftcreatedir", ProtocolRole.CLIENT,
|
||||
new CommandSingleParameter("cid", Integer.toString(channelId)),
|
||||
new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword),
|
||||
new CommandSingleParameter("dirname", dirPath));
|
||||
socket.executeCommand(cmd).complete();
|
||||
}
|
||||
|
||||
/** Deletes a file or (recursively) a directory at {@code fullPath}. */
|
||||
public void delete(int channelId, String channelPassword, String fullPath)
|
||||
throws Exception {
|
||||
SingleCommand cmd = new SingleCommand("ftdeletefile", ProtocolRole.CLIENT,
|
||||
new CommandSingleParameter("cid", Integer.toString(channelId)),
|
||||
new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword),
|
||||
new CommandSingleParameter("name", fullPath));
|
||||
socket.executeCommand(cmd).complete();
|
||||
}
|
||||
|
||||
/** Renames or moves a file within the same channel. */
|
||||
public void rename(int channelId, String channelPassword, String oldFullPath, String newFullPath)
|
||||
throws Exception {
|
||||
SingleCommand cmd = new SingleCommand("ftrenamefile", ProtocolRole.CLIENT,
|
||||
new CommandSingleParameter("cid", Integer.toString(channelId)),
|
||||
new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword),
|
||||
new CommandSingleParameter("oldname", oldFullPath),
|
||||
new CommandSingleParameter("newname", newFullPath));
|
||||
socket.executeCommand(cmd).complete();
|
||||
}
|
||||
|
||||
// ---- byte transfers ----
|
||||
|
||||
/**
|
||||
* Starts downloading {@code remoteFullPath} from the channel to {@code target}.
|
||||
* Returns immediately with a handle whose progress the caller can observe; the
|
||||
* copy proceeds on a background thread.
|
||||
*/
|
||||
public FileTransfer download(int channelId, String channelPassword, String remoteFullPath,
|
||||
File target, FileTransfer.Listener listener) {
|
||||
FileTransfer transfer = new FileTransfer(FileTransfer.Direction.DOWNLOAD, channelId,
|
||||
fileName(remoteFullPath), target, -1, listener);
|
||||
transferPool.execute(() -> runDownload(channelId, channelPassword, remoteFullPath, transfer));
|
||||
return transfer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts uploading {@code source} into the channel at {@code remoteFullPath}.
|
||||
* Returns immediately with a handle whose progress the caller can observe.
|
||||
*/
|
||||
public FileTransfer upload(int channelId, String channelPassword, String remoteFullPath,
|
||||
File source, boolean overwrite, FileTransfer.Listener listener) {
|
||||
FileTransfer transfer = new FileTransfer(FileTransfer.Direction.UPLOAD, channelId,
|
||||
fileName(remoteFullPath), source, source.length(), listener);
|
||||
transferPool.execute(() -> runUpload(channelId, channelPassword, remoteFullPath, source, overwrite, transfer));
|
||||
return transfer;
|
||||
}
|
||||
|
||||
private void runDownload(int channelId, String channelPassword, String remoteFullPath,
|
||||
FileTransfer transfer) {
|
||||
try {
|
||||
int ftfid = clientTransferId.getAndIncrement();
|
||||
SingleCommand cmd = new SingleCommand("ftinitdownload", ProtocolRole.CLIENT,
|
||||
new CommandSingleParameter("clientftfid", Integer.toString(ftfid)),
|
||||
new CommandSingleParameter("name", remoteFullPath),
|
||||
new CommandSingleParameter("cid", Integer.toString(channelId)),
|
||||
new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword),
|
||||
new CommandSingleParameter("seekpos", "0"),
|
||||
new CommandSingleParameter("proto", "0"));
|
||||
|
||||
FileTransferParameters params = negotiate(ftfid, cmd);
|
||||
long size = params.getFileSize();
|
||||
transfer.setTotalBytes(size);
|
||||
|
||||
try (Socket fileSocket = openFileSocket(params);
|
||||
InputStream in = new BufferedInputStream(fileSocket.getInputStream());
|
||||
OutputStream fileOut = new BufferedOutputStream(new FileOutputStream(transfer.getLocalFile()))) {
|
||||
|
||||
sendKey(fileSocket, params);
|
||||
transfer.markActive();
|
||||
|
||||
byte[] buffer = new byte[BUFFER_SIZE];
|
||||
long remaining = size;
|
||||
while (remaining > 0) {
|
||||
if (transfer.isCancelRequested()) {
|
||||
transfer.markCancelled();
|
||||
deleteQuietly(transfer.getLocalFile());
|
||||
return;
|
||||
}
|
||||
int want = (int) Math.min(buffer.length, remaining);
|
||||
int read = in.read(buffer, 0, want);
|
||||
if (read < 0) throw new IOException("File server closed the connection early");
|
||||
fileOut.write(buffer, 0, read);
|
||||
remaining -= read;
|
||||
transfer.addTransferred(read);
|
||||
}
|
||||
}
|
||||
transfer.markCompleted();
|
||||
} catch (Exception e) {
|
||||
transfer.markFailed(rootMessage(e));
|
||||
deleteQuietly(transfer.getLocalFile());
|
||||
}
|
||||
}
|
||||
|
||||
private void runUpload(int channelId, String channelPassword, String remoteFullPath,
|
||||
File source, boolean overwrite, FileTransfer transfer) {
|
||||
try {
|
||||
long size = source.length();
|
||||
int ftfid = clientTransferId.getAndIncrement();
|
||||
SingleCommand cmd = new SingleCommand("ftinitupload", ProtocolRole.CLIENT,
|
||||
new CommandSingleParameter("clientftfid", Integer.toString(ftfid)),
|
||||
new CommandSingleParameter("name", remoteFullPath),
|
||||
new CommandSingleParameter("cid", Integer.toString(channelId)),
|
||||
new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword),
|
||||
new CommandSingleParameter("size", Long.toString(size)),
|
||||
new CommandSingleParameter("overwrite", overwrite ? "1" : "0"),
|
||||
new CommandSingleParameter("resume", "0"),
|
||||
new CommandSingleParameter("proto", "0"));
|
||||
|
||||
FileTransferParameters params = negotiate(ftfid, cmd);
|
||||
// The server may already hold a prefix of the file (resume); start after it.
|
||||
long seekpos = params.getMap().containsKey("seekpos") ? params.getLong("seekpos") : 0;
|
||||
if (seekpos < 0 || seekpos > size) seekpos = 0;
|
||||
|
||||
try (Socket fileSocket = openFileSocket(params);
|
||||
InputStream fileIn = new BufferedInputStream(new FileInputStream(source));
|
||||
OutputStream out = new BufferedOutputStream(fileSocket.getOutputStream())) {
|
||||
|
||||
sendKey(fileSocket, params);
|
||||
transfer.markActive();
|
||||
|
||||
if (seekpos > 0) {
|
||||
skipFully(fileIn, seekpos);
|
||||
transfer.addTransferred(seekpos);
|
||||
}
|
||||
|
||||
byte[] buffer = new byte[BUFFER_SIZE];
|
||||
long remaining = size - seekpos;
|
||||
while (remaining > 0) {
|
||||
if (transfer.isCancelRequested()) {
|
||||
transfer.markCancelled();
|
||||
return;
|
||||
}
|
||||
int want = (int) Math.min(buffer.length, remaining);
|
||||
int read = fileIn.read(buffer, 0, want);
|
||||
if (read < 0) break; // file shorter than announced; stop
|
||||
out.write(buffer, 0, read);
|
||||
remaining -= read;
|
||||
transfer.addTransferred(read);
|
||||
}
|
||||
out.flush();
|
||||
}
|
||||
transfer.markCompleted();
|
||||
} catch (Exception e) {
|
||||
transfer.markFailed(rootMessage(e));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an {@code ftinit*} command and returns the negotiated parameters. The server
|
||||
* acknowledges the command itself, then reports the transfer's key/host/port
|
||||
* asynchronously via a {@code notifystart*} event (or a {@code notifystatusfiletransfer}
|
||||
* on refusal), which {@link #handleFileTransferEvent} feeds back through {@code pendingInits}.
|
||||
*/
|
||||
private FileTransferParameters negotiate(int clientTransferId, SingleCommand cmd) throws Exception {
|
||||
CompletableFuture<Map<String, String>> future = new CompletableFuture<>();
|
||||
pendingInits.put(clientTransferId, future);
|
||||
try {
|
||||
// Await the command-level acknowledgement; a hard error (e.g. bad path) throws here.
|
||||
socket.executeCommand(cmd).complete();
|
||||
Map<String, String> result;
|
||||
try {
|
||||
result = future.get(NEGOTIATE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
|
||||
} catch (ExecutionException e) {
|
||||
Throwable cause = e.getCause();
|
||||
throw cause instanceof Exception ? (Exception) cause : e;
|
||||
} catch (TimeoutException e) {
|
||||
throw new IOException("Timed out waiting for the server to start the transfer");
|
||||
}
|
||||
FileTransferParameters params = new FileTransferParameters(result);
|
||||
String key = params.getFileTransferKey();
|
||||
if (key == null || key.isEmpty()) throw new IOException("Server refused the file transfer");
|
||||
return params;
|
||||
} finally {
|
||||
pendingInits.remove(clientTransferId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes an incoming file-transfer notification to the negotiation that is waiting for
|
||||
* it. {@code notifystartdownload}/{@code notifystartupload} carry the key, host and port;
|
||||
* {@code notifystatusfiletransfer} signals a non-zero status (a refusal) before the
|
||||
* transfer starts.
|
||||
*/
|
||||
private void handleFileTransferEvent(UnknownTeamspeakEvent e) {
|
||||
String command = e.getCommand();
|
||||
if (command == null) return;
|
||||
Map<String, String> map = e.getMap();
|
||||
Integer ftfid = tryParseInt(map.get("clientftfid"));
|
||||
if (ftfid == null) return;
|
||||
CompletableFuture<Map<String, String>> future = pendingInits.get(ftfid);
|
||||
if (future == null) return;
|
||||
|
||||
if (command.equals("notifystartdownload") || command.equals("notifystartupload")) {
|
||||
future.complete(map);
|
||||
} else if (command.equals("notifystatusfiletransfer")) {
|
||||
int status = (int) parseLong(map.get("status"));
|
||||
if (status != 0) {
|
||||
String msg = map.get("msg");
|
||||
future.completeExceptionally(
|
||||
new IOException(msg != null && !msg.isEmpty() ? msg : "File transfer failed (status " + status + ")"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Socket openFileSocket(FileTransferParameters params) throws IOException {
|
||||
Socket socket = new Socket();
|
||||
socket.connect(new InetSocketAddress(resolveHost(params.getFileServerHost()),
|
||||
params.getFileServerPort()), CONNECT_TIMEOUT_MS);
|
||||
return socket;
|
||||
}
|
||||
|
||||
/** Sends the negotiated one-time key that authorises this connection to the file port. */
|
||||
private static void sendKey(Socket fileSocket, FileTransferParameters params) throws IOException {
|
||||
OutputStream out = fileSocket.getOutputStream();
|
||||
out.write(params.getFileTransferKey().getBytes(StandardCharsets.US_ASCII));
|
||||
out.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the host to reach the file server. The {@code ip} the server reports may be
|
||||
* a comma-separated list, empty, or a wildcard; in those cases fall back to the host
|
||||
* we are already connected to.
|
||||
*/
|
||||
private String resolveHost(String reported) {
|
||||
if (reported != null) {
|
||||
String first = reported.split(",")[0].trim();
|
||||
if (!first.isEmpty() && !first.startsWith("0.0.0.0")) return first;
|
||||
}
|
||||
return fallbackHost.get();
|
||||
}
|
||||
|
||||
private static void deleteQuietly(File file) {
|
||||
if (file != null && file.isFile()) {
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
|
||||
private static void skipFully(InputStream in, long n) throws IOException {
|
||||
long remaining = n;
|
||||
while (remaining > 0) {
|
||||
long skipped = in.skip(remaining);
|
||||
if (skipped <= 0) {
|
||||
if (in.read() < 0) throw new IOException("Unexpected end of file while seeking");
|
||||
skipped = 1;
|
||||
}
|
||||
remaining -= skipped;
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
socket.removeListener(ftEventListener);
|
||||
for (CompletableFuture<Map<String, String>> future : pendingInits.values()) {
|
||||
future.completeExceptionally(new IOException("Disconnected"));
|
||||
}
|
||||
pendingInits.clear();
|
||||
transferPool.shutdownNow();
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
private static String fileName(String fullPath) {
|
||||
int slash = fullPath.lastIndexOf('/');
|
||||
return slash < 0 ? fullPath : fullPath.substring(slash + 1);
|
||||
}
|
||||
|
||||
private static long parseLong(String s) {
|
||||
if (s == null || s.isEmpty()) return 0;
|
||||
try {
|
||||
return Long.parseLong(s.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static Integer tryParseInt(String s) {
|
||||
if (s == null || s.isEmpty()) return null;
|
||||
try {
|
||||
return Integer.parseInt(s.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String rootMessage(Throwable t) {
|
||||
Throwable r = t;
|
||||
while (r.getCause() != null && r.getCause() != r) r = r.getCause();
|
||||
String m = r.getMessage();
|
||||
return m != null ? m : r.getClass().getSimpleName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.ts3client.net.filetransfer;
|
||||
|
||||
/**
|
||||
* One entry in a channel's file repository, as returned by {@code ftgetfilelist}.
|
||||
* A UI-facing value type that keeps the reusable core free of ts3j API classes.
|
||||
*/
|
||||
public final class RemoteFile {
|
||||
|
||||
private final String name;
|
||||
/** Parent directory path, always ending in {@code /} (e.g. {@code /} or {@code /sub/}). */
|
||||
private final String parentPath;
|
||||
private final long size;
|
||||
private final boolean directory;
|
||||
private final long lastModifiedEpochSec;
|
||||
|
||||
public RemoteFile(String name, String parentPath, long size, boolean directory, long lastModifiedEpochSec) {
|
||||
this.name = name;
|
||||
this.parentPath = parentPath == null || parentPath.isEmpty() ? "/" : parentPath;
|
||||
this.size = size;
|
||||
this.directory = directory;
|
||||
this.lastModifiedEpochSec = lastModifiedEpochSec;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getParentPath() {
|
||||
return parentPath;
|
||||
}
|
||||
|
||||
/** Full server path including the file name, e.g. {@code /sub/clip.ogg}. */
|
||||
public String getFullPath() {
|
||||
String base = parentPath.endsWith("/") ? parentPath : parentPath + "/";
|
||||
return base + name;
|
||||
}
|
||||
|
||||
public long getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
public boolean isDirectory() {
|
||||
return directory;
|
||||
}
|
||||
|
||||
public long getLastModifiedEpochSec() {
|
||||
return lastModifiedEpochSec;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user