feat: 增强 Transfers 页面文件浏览功能
- 在 SftpFilePickerModal 中添加搜索功能 - 添加显示/隐藏文件切换按钮(参考 SftpView) - Remote->Many 模式下目标连接列表自动排除源连接 - 全选功能自动排除源连接 - 添加空状态提示信息 - 优化用户体验和交互逻辑
This commit is contained in:
17
AGENTS.md
17
AGENTS.md
@@ -150,17 +150,26 @@
|
|||||||
- 检查未提交敏感信息与本地配置
|
- 检查未提交敏感信息与本地配置
|
||||||
- 仅提交与需求直接相关的文件
|
- 仅提交与需求直接相关的文件
|
||||||
|
|
||||||
## 9) 文档与规则文件检查结果
|
## 9) Makefile 快捷命令(仓库根目录)
|
||||||
|
|
||||||
- `AGENTS.md`:本文件为新建(仓库根目录)
|
- `make build`:构建 Docker 镜像
|
||||||
|
- `make up`:构建并后台启动服务
|
||||||
|
- `make down`:停止并移除服务
|
||||||
|
- `make restart`:重启服务
|
||||||
|
- `make logs`:查看服务日志
|
||||||
|
- `make ps`:查看服务状态
|
||||||
|
|
||||||
|
## 10) 文档与规则文件检查结果
|
||||||
|
|
||||||
|
- `AGENTS.md`:本文件(仓库根目录)
|
||||||
- Cursor 规则:未发现 `.cursor/rules/` 或 `.cursorrules`
|
- Cursor 规则:未发现 `.cursor/rules/` 或 `.cursorrules`
|
||||||
- Copilot 规则:未发现 `.github/copilot-instructions.md`
|
- Copilot 规则:未发现 `.github/copilot-instructions.md`
|
||||||
|
|
||||||
若未来新增上述规则文件,agents 必须先读取并将其视为高优先级约束。
|
若未来新增上述规则文件,agents 必须先读取并将其视为高优先级约束。
|
||||||
|
|
||||||
## 10) 近期修复记录(2026-03-11)
|
## 11) 近期修复记录
|
||||||
|
|
||||||
### 10.1 Docker 启动失败修复
|
### 11.1 Docker 启动失败修复
|
||||||
|
|
||||||
**问题现象**
|
**问题现象**
|
||||||
```text
|
```text
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ ssh-manager/
|
|||||||
│ ├── components/
|
│ ├── components/
|
||||||
│ ├── stores/
|
│ ├── stores/
|
||||||
│ └── api/
|
│ └── api/
|
||||||
└── design-system/ # UI/UX 规范
|
└── docs/design-system/ # UI/UX 规范
|
||||||
```
|
```
|
||||||
|
|
||||||
## 配置
|
## 配置
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ public class SftpSessionCleanupTask {
|
|||||||
@Value("${sshmanager.sftp-session-timeout-minutes:30}")
|
@Value("${sshmanager.sftp-session-timeout-minutes:30}")
|
||||||
private int sessionTimeoutMinutes;
|
private int sessionTimeoutMinutes;
|
||||||
|
|
||||||
|
@Value("${sshmanager.transfer-task-timeout-minutes:30}")
|
||||||
|
private int transferTaskTimeoutMinutes;
|
||||||
|
|
||||||
private final SftpController sftpController;
|
private final SftpController sftpController;
|
||||||
|
|
||||||
public SftpSessionCleanupTask(SftpController sftpController) {
|
public SftpSessionCleanupTask(SftpController sftpController) {
|
||||||
@@ -25,5 +28,6 @@ public class SftpSessionCleanupTask {
|
|||||||
public void cleanupIdleSessions() {
|
public void cleanupIdleSessions() {
|
||||||
log.debug("Running SFTP session cleanup task");
|
log.debug("Running SFTP session cleanup task");
|
||||||
sftpController.cleanupExpiredSessions(sessionTimeoutMinutes);
|
sftpController.cleanupExpiredSessions(sessionTimeoutMinutes);
|
||||||
|
sftpController.cleanupExpiredTransferTasks(transferTaskTimeoutMinutes);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,11 +17,19 @@ import org.springframework.stereotype.Component;
|
|||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
@@ -38,6 +46,10 @@ public class SftpController {
|
|||||||
|
|
||||||
private final Map<String, SftpService.SftpSession> sessions = new ConcurrentHashMap<>();
|
private final Map<String, SftpService.SftpSession> sessions = new ConcurrentHashMap<>();
|
||||||
private final Map<String, Object> sessionLocks = new ConcurrentHashMap<>();
|
private final Map<String, Object> sessionLocks = new ConcurrentHashMap<>();
|
||||||
|
private final Map<String, TransferTaskStatus> transferTasks = new ConcurrentHashMap<>();
|
||||||
|
private final Map<String, UploadTaskStatus> uploadTasks = new ConcurrentHashMap<>();
|
||||||
|
private final ExecutorService transferTaskExecutor = Executors.newCachedThreadPool();
|
||||||
|
private final Map<String, CopyOnWriteArrayList<SseEmitter>> taskEmitters = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
public SftpController(ConnectionService connectionService,
|
public SftpController(ConnectionService connectionService,
|
||||||
UserRepository userRepository,
|
UserRepository userRepository,
|
||||||
@@ -56,6 +68,14 @@ public class SftpController {
|
|||||||
return userId + ":" + connectionId;
|
return userId + ":" + connectionId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String transferTaskKey(Long userId, String taskId) {
|
||||||
|
return userId + ":" + taskId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String uploadTaskKey(Long userId, String taskId) {
|
||||||
|
return userId + ":" + taskId;
|
||||||
|
}
|
||||||
|
|
||||||
private <T> T withSessionLock(String key, Supplier<T> action) {
|
private <T> T withSessionLock(String key, Supplier<T> action) {
|
||||||
Object lock = sessionLocks.computeIfAbsent(key, k -> new Object());
|
Object lock = sessionLocks.computeIfAbsent(key, k -> new Object());
|
||||||
synchronized (lock) {
|
synchronized (lock) {
|
||||||
@@ -143,6 +163,64 @@ public class SftpController {
|
|||||||
return operation + " failed";
|
return operation + " failed";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<Map<String, String>> validateTransferPaths(String sourcePath, String targetPath) {
|
||||||
|
if (sourcePath == null || sourcePath.trim().isEmpty()) {
|
||||||
|
Map<String, String> err = new HashMap<>();
|
||||||
|
err.put("error", "sourcePath is required");
|
||||||
|
return ResponseEntity.badRequest().body(err);
|
||||||
|
}
|
||||||
|
if (targetPath == null || targetPath.trim().isEmpty()) {
|
||||||
|
Map<String, String> err = new HashMap<>();
|
||||||
|
err.put("error", "targetPath is required");
|
||||||
|
return ResponseEntity.badRequest().body(err);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void executeTransfer(Long userId,
|
||||||
|
Long sourceConnectionId,
|
||||||
|
String sourcePath,
|
||||||
|
Long targetConnectionId,
|
||||||
|
String targetPath,
|
||||||
|
TransferTaskStatus status) throws Exception {
|
||||||
|
String cleanSourcePath = sourcePath.trim();
|
||||||
|
String cleanTargetPath = targetPath.trim();
|
||||||
|
String sourceKey = sessionKey(userId, sourceConnectionId);
|
||||||
|
String targetKey = sessionKey(userId, targetConnectionId);
|
||||||
|
|
||||||
|
withTwoSessionLocks(sourceKey, targetKey, () -> {
|
||||||
|
try {
|
||||||
|
SftpService.SftpSession sourceSession = getOrCreateSession(sourceConnectionId, userId);
|
||||||
|
SftpService.SftpSession targetSession = getOrCreateSession(targetConnectionId, userId);
|
||||||
|
sftpService.transferRemote(sourceSession, cleanSourcePath, targetSession, cleanTargetPath,
|
||||||
|
new SftpService.TransferProgressListener() {
|
||||||
|
@Override
|
||||||
|
public void onStart(long totalBytes) {
|
||||||
|
status.setProgress(0, totalBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onProgress(long transferredBytes, long totalBytes) {
|
||||||
|
status.setProgress(transferredBytes, totalBytes);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return null;
|
||||||
|
} catch (Exception e) {
|
||||||
|
SftpService.SftpSession source = sessions.remove(sourceKey);
|
||||||
|
if (source != null) {
|
||||||
|
source.disconnect();
|
||||||
|
}
|
||||||
|
if (!sourceKey.equals(targetKey)) {
|
||||||
|
SftpService.SftpSession target = sessions.remove(targetKey);
|
||||||
|
if (target != null) {
|
||||||
|
target.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/pwd")
|
@GetMapping("/pwd")
|
||||||
public ResponseEntity<Map<String, String>> pwd(
|
public ResponseEntity<Map<String, String>> pwd(
|
||||||
@RequestParam Long connectionId,
|
@RequestParam Long connectionId,
|
||||||
@@ -207,26 +285,49 @@ public class SftpController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/upload")
|
@PostMapping("/upload")
|
||||||
public ResponseEntity<Map<String, String>> upload(
|
public ResponseEntity<Map<String, Object>> upload(
|
||||||
@RequestParam Long connectionId,
|
@RequestParam Long connectionId,
|
||||||
@RequestParam String path,
|
@RequestParam String path,
|
||||||
@RequestParam("file") MultipartFile file,
|
@RequestParam("file") MultipartFile file,
|
||||||
Authentication authentication) {
|
Authentication authentication) {
|
||||||
try {
|
try {
|
||||||
Long userId = getCurrentUserId(authentication);
|
Long userId = getCurrentUserId(authentication);
|
||||||
|
String taskId = UUID.randomUUID().toString();
|
||||||
|
String taskKey = uploadTaskKey(userId, taskId);
|
||||||
|
|
||||||
|
UploadTaskStatus status = new UploadTaskStatus(taskId, userId, connectionId,
|
||||||
|
path, file.getOriginalFilename(), file.getSize());
|
||||||
|
status.setController(this);
|
||||||
|
uploadTasks.put(taskKey, status);
|
||||||
|
|
||||||
|
Future<?> future = transferTaskExecutor.submit(() -> {
|
||||||
|
status.setStatus("running");
|
||||||
String key = sessionKey(userId, connectionId);
|
String key = sessionKey(userId, connectionId);
|
||||||
return withSessionLock(key, () -> {
|
try {
|
||||||
|
withSessionLock(key, () -> {
|
||||||
try {
|
try {
|
||||||
SftpService.SftpSession session = getOrCreateSession(connectionId, userId);
|
SftpService.SftpSession session = getOrCreateSession(connectionId, userId);
|
||||||
String remotePath = (path == null || path.isEmpty() || path.equals("/"))
|
String remotePath = (path == null || path.isEmpty() || path.equals("/"))
|
||||||
? "/" + file.getOriginalFilename()
|
? "/" + file.getOriginalFilename()
|
||||||
: (path.endsWith("/") ? path + file.getOriginalFilename() : path + "/" + file.getOriginalFilename());
|
: (path.endsWith("/") ? path + file.getOriginalFilename() : path + "/" + file.getOriginalFilename());
|
||||||
|
|
||||||
|
AtomicLong transferred = new AtomicLong(0);
|
||||||
try (java.io.InputStream in = file.getInputStream()) {
|
try (java.io.InputStream in = file.getInputStream()) {
|
||||||
sftpService.upload(session, remotePath, in);
|
sftpService.upload(session, remotePath, in, new SftpService.TransferProgressListener() {
|
||||||
|
@Override
|
||||||
|
public void onStart(long totalBytes) {
|
||||||
|
status.setProgress(0, totalBytes);
|
||||||
}
|
}
|
||||||
Map<String, String> result = new HashMap<>();
|
|
||||||
result.put("message", "Uploaded");
|
@Override
|
||||||
return ResponseEntity.ok(result);
|
public void onProgress(long count, long totalBytes) {
|
||||||
|
long current = transferred.addAndGet(count);
|
||||||
|
status.setProgress(current, status.getTotalBytes());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
status.markSuccess();
|
||||||
|
return null;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
SftpService.SftpSession existing = sessions.remove(key);
|
SftpService.SftpSession existing = sessions.remove(key);
|
||||||
if (existing != null) {
|
if (existing != null) {
|
||||||
@@ -236,7 +337,17 @@ public class SftpController {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Map<String, String> error = new HashMap<>();
|
status.markError(e.getMessage() != null ? e.getMessage() : "Upload failed");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
status.setFuture(future);
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("taskId", taskId);
|
||||||
|
result.put("message", "Upload started");
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
} catch (Exception e) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
error.put("error", e.getMessage());
|
error.put("error", e.getMessage());
|
||||||
return ResponseEntity.status(500).body(error);
|
return ResponseEntity.status(500).body(error);
|
||||||
}
|
}
|
||||||
@@ -343,42 +454,13 @@ public class SftpController {
|
|||||||
Authentication authentication) {
|
Authentication authentication) {
|
||||||
try {
|
try {
|
||||||
Long userId = getCurrentUserId(authentication);
|
Long userId = getCurrentUserId(authentication);
|
||||||
if (sourcePath == null || sourcePath.trim().isEmpty()) {
|
ResponseEntity<Map<String, String>> validation = validateTransferPaths(sourcePath, targetPath);
|
||||||
Map<String, String> err = new HashMap<>();
|
if (validation != null) {
|
||||||
err.put("error", "sourcePath is required");
|
return validation;
|
||||||
return ResponseEntity.badRequest().body(err);
|
|
||||||
}
|
}
|
||||||
if (targetPath == null || targetPath.trim().isEmpty()) {
|
TransferTaskStatus status = new TransferTaskStatus(UUID.randomUUID().toString(), userId, sourceConnectionId, targetConnectionId,
|
||||||
Map<String, String> err = new HashMap<>();
|
sourcePath.trim(), targetPath.trim());
|
||||||
err.put("error", "targetPath is required");
|
executeTransfer(userId, sourceConnectionId, sourcePath, targetConnectionId, targetPath, status);
|
||||||
return ResponseEntity.badRequest().body(err);
|
|
||||||
}
|
|
||||||
String sourceKey = sessionKey(userId, sourceConnectionId);
|
|
||||||
String targetKey = sessionKey(userId, targetConnectionId);
|
|
||||||
withTwoSessionLocks(sourceKey, targetKey, () -> {
|
|
||||||
try {
|
|
||||||
SftpService.SftpSession sourceSession = getOrCreateSession(sourceConnectionId, userId);
|
|
||||||
SftpService.SftpSession targetSession = getOrCreateSession(targetConnectionId, userId);
|
|
||||||
if (sourceConnectionId.equals(targetConnectionId)) {
|
|
||||||
sftpService.rename(sourceSession, sourcePath.trim(), targetPath.trim());
|
|
||||||
} else {
|
|
||||||
sftpService.transferRemote(sourceSession, sourcePath.trim(), targetSession, targetPath.trim());
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
} catch (Exception e) {
|
|
||||||
SftpService.SftpSession source = sessions.remove(sourceKey);
|
|
||||||
if (source != null) {
|
|
||||||
source.disconnect();
|
|
||||||
}
|
|
||||||
if (!sourceKey.equals(targetKey)) {
|
|
||||||
SftpService.SftpSession target = sessions.remove(targetKey);
|
|
||||||
if (target != null) {
|
|
||||||
target.disconnect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Map<String, String> result = new HashMap<>();
|
Map<String, String> result = new HashMap<>();
|
||||||
result.put("message", "Transferred");
|
result.put("message", "Transferred");
|
||||||
return ResponseEntity.ok(result);
|
return ResponseEntity.ok(result);
|
||||||
@@ -389,6 +471,206 @@ public class SftpController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/transfer-remote/tasks")
|
||||||
|
public ResponseEntity<Map<String, Object>> createTransferRemoteTask(
|
||||||
|
@RequestParam Long sourceConnectionId,
|
||||||
|
@RequestParam String sourcePath,
|
||||||
|
@RequestParam Long targetConnectionId,
|
||||||
|
@RequestParam String targetPath,
|
||||||
|
Authentication authentication) {
|
||||||
|
Long userId = getCurrentUserId(authentication);
|
||||||
|
ResponseEntity<Map<String, String>> validation = validateTransferPaths(sourcePath, targetPath);
|
||||||
|
if (validation != null) {
|
||||||
|
Map<String, Object> err = new HashMap<>();
|
||||||
|
err.putAll(validation.getBody());
|
||||||
|
return ResponseEntity.status(validation.getStatusCode()).body(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
TransferTaskStatus status = new TransferTaskStatus(UUID.randomUUID().toString(), userId, sourceConnectionId, targetConnectionId,
|
||||||
|
sourcePath.trim(), targetPath.trim());
|
||||||
|
status.setController(this);
|
||||||
|
String taskKey = transferTaskKey(userId, status.getTaskId());
|
||||||
|
transferTasks.put(taskKey, status);
|
||||||
|
|
||||||
|
Future<?> future = transferTaskExecutor.submit(() -> {
|
||||||
|
status.setStatus("running");
|
||||||
|
try {
|
||||||
|
if (Thread.currentThread().isInterrupted()) {
|
||||||
|
status.markCancelled();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
executeTransfer(userId, sourceConnectionId, sourcePath, targetConnectionId, targetPath, status);
|
||||||
|
status.markSuccess();
|
||||||
|
} catch (Exception e) {
|
||||||
|
if (e instanceof InterruptedException || Thread.currentThread().isInterrupted()) {
|
||||||
|
status.markCancelled();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
status.markError(toSftpErrorMessage(e, sourcePath, "transfer"));
|
||||||
|
log.warn("SFTP transfer task failed: taskId={}, sourceConnectionId={}, sourcePath={}, targetConnectionId={}, targetPath={}, error={}",
|
||||||
|
status.getTaskId(), sourceConnectionId, sourcePath, targetConnectionId, targetPath, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
status.setFuture(future);
|
||||||
|
|
||||||
|
return ResponseEntity.ok(status.toResponse());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/transfer-remote/tasks/{taskId}")
|
||||||
|
public ResponseEntity<Map<String, Object>> getTransferRemoteTask(
|
||||||
|
@PathVariable String taskId,
|
||||||
|
Authentication authentication) {
|
||||||
|
Long userId = getCurrentUserId(authentication);
|
||||||
|
TransferTaskStatus status = transferTasks.get(transferTaskKey(userId, taskId));
|
||||||
|
if (status == null) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("error", "Transfer task not found");
|
||||||
|
return ResponseEntity.status(404).body(error);
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(status.toResponse());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/upload/tasks/{taskId}")
|
||||||
|
public ResponseEntity<Map<String, Object>> getUploadTask(
|
||||||
|
@PathVariable String taskId,
|
||||||
|
Authentication authentication) {
|
||||||
|
Long userId = getCurrentUserId(authentication);
|
||||||
|
UploadTaskStatus status = uploadTasks.get(uploadTaskKey(userId, taskId));
|
||||||
|
if (status == null) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("error", "Upload task not found");
|
||||||
|
return ResponseEntity.status(404).body(error);
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(status.toResponse());
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/transfer-remote/tasks/{taskId}")
|
||||||
|
public ResponseEntity<Map<String, Object>> cancelTransferRemoteTask(
|
||||||
|
@PathVariable String taskId,
|
||||||
|
Authentication authentication) {
|
||||||
|
Long userId = getCurrentUserId(authentication);
|
||||||
|
TransferTaskStatus status = transferTasks.get(transferTaskKey(userId, taskId));
|
||||||
|
if (status == null) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("error", "Transfer task not found");
|
||||||
|
return ResponseEntity.status(404).body(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean cancelled = status.cancel();
|
||||||
|
Map<String, Object> result = status.toResponse();
|
||||||
|
result.put("cancelRequested", cancelled);
|
||||||
|
if (!cancelled) {
|
||||||
|
result.put("message", "Task already running or finished; current transfer cannot be interrupted safely");
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/transfer-remote/tasks/{taskId}/progress")
|
||||||
|
public SseEmitter streamTransferProgress(
|
||||||
|
@PathVariable String taskId,
|
||||||
|
Authentication authentication) {
|
||||||
|
Long userId = getCurrentUserId(authentication);
|
||||||
|
String taskKey = transferTaskKey(userId, taskId);
|
||||||
|
TransferTaskStatus status = transferTasks.get(taskKey);
|
||||||
|
|
||||||
|
SseEmitter emitter = new SseEmitter(300000L); // 5 minutes timeout
|
||||||
|
|
||||||
|
if (status == null) {
|
||||||
|
try {
|
||||||
|
Map<String, String> error = new HashMap<>();
|
||||||
|
error.put("error", "Task not found");
|
||||||
|
emitter.send(SseEmitter.event().name("error").data(error));
|
||||||
|
emitter.complete();
|
||||||
|
} catch (IOException e) {
|
||||||
|
emitter.completeWithError(e);
|
||||||
|
}
|
||||||
|
return emitter;
|
||||||
|
}
|
||||||
|
|
||||||
|
taskEmitters.computeIfAbsent(taskKey, k -> new CopyOnWriteArrayList<>()).add(emitter);
|
||||||
|
|
||||||
|
emitter.onCompletion(() -> removeEmitter(taskKey, emitter));
|
||||||
|
emitter.onTimeout(() -> removeEmitter(taskKey, emitter));
|
||||||
|
emitter.onError((e) -> removeEmitter(taskKey, emitter));
|
||||||
|
|
||||||
|
// Send initial status
|
||||||
|
try {
|
||||||
|
emitter.send(SseEmitter.event().name("progress").data(status.toResponse()));
|
||||||
|
} catch (IOException e) {
|
||||||
|
removeEmitter(taskKey, emitter);
|
||||||
|
}
|
||||||
|
|
||||||
|
return emitter;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/upload/tasks/{taskId}/progress")
|
||||||
|
public SseEmitter streamUploadProgress(
|
||||||
|
@PathVariable String taskId,
|
||||||
|
Authentication authentication) {
|
||||||
|
Long userId = getCurrentUserId(authentication);
|
||||||
|
String taskKey = uploadTaskKey(userId, taskId);
|
||||||
|
UploadTaskStatus status = uploadTasks.get(taskKey);
|
||||||
|
|
||||||
|
SseEmitter emitter = new SseEmitter(300000L); // 5 minutes timeout
|
||||||
|
|
||||||
|
if (status == null) {
|
||||||
|
try {
|
||||||
|
Map<String, String> error = new HashMap<>();
|
||||||
|
error.put("error", "Task not found");
|
||||||
|
emitter.send(SseEmitter.event().name("error").data(error));
|
||||||
|
emitter.complete();
|
||||||
|
} catch (IOException e) {
|
||||||
|
emitter.completeWithError(e);
|
||||||
|
}
|
||||||
|
return emitter;
|
||||||
|
}
|
||||||
|
|
||||||
|
taskEmitters.computeIfAbsent(taskKey, k -> new CopyOnWriteArrayList<>()).add(emitter);
|
||||||
|
|
||||||
|
emitter.onCompletion(() -> removeEmitter(taskKey, emitter));
|
||||||
|
emitter.onTimeout(() -> removeEmitter(taskKey, emitter));
|
||||||
|
emitter.onError((e) -> removeEmitter(taskKey, emitter));
|
||||||
|
|
||||||
|
// Send initial status
|
||||||
|
try {
|
||||||
|
emitter.send(SseEmitter.event().name("progress").data(status.toResponse()));
|
||||||
|
} catch (IOException e) {
|
||||||
|
removeEmitter(taskKey, emitter);
|
||||||
|
}
|
||||||
|
|
||||||
|
return emitter;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void removeEmitter(String taskKey, SseEmitter emitter) {
|
||||||
|
CopyOnWriteArrayList<SseEmitter> emitters = taskEmitters.get(taskKey);
|
||||||
|
if (emitters != null) {
|
||||||
|
emitters.remove(emitter);
|
||||||
|
if (emitters.isEmpty()) {
|
||||||
|
taskEmitters.remove(taskKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void broadcastProgress(String taskKey, Map<String, Object> data) {
|
||||||
|
CopyOnWriteArrayList<SseEmitter> emitters = taskEmitters.get(taskKey);
|
||||||
|
if (emitters == null || emitters.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<SseEmitter> deadEmitters = new java.util.ArrayList<>();
|
||||||
|
for (SseEmitter emitter : emitters) {
|
||||||
|
try {
|
||||||
|
emitter.send(SseEmitter.event().name("progress").data(data));
|
||||||
|
} catch (Exception e) {
|
||||||
|
deadEmitters.add(emitter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (SseEmitter dead : deadEmitters) {
|
||||||
|
removeEmitter(taskKey, dead);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@PostMapping("/disconnect")
|
@PostMapping("/disconnect")
|
||||||
public ResponseEntity<Map<String, String>> disconnect(
|
public ResponseEntity<Map<String, String>> disconnect(
|
||||||
@RequestParam Long connectionId,
|
@RequestParam Long connectionId,
|
||||||
@@ -419,6 +701,12 @@ public class SftpController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void cleanupExpiredTransferTasks(int timeoutMinutes) {
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
long timeoutMillis = timeoutMinutes * 60L * 1000L;
|
||||||
|
transferTasks.entrySet().removeIf(entry -> entry.getValue().isExpired(now, timeoutMillis));
|
||||||
|
}
|
||||||
|
|
||||||
private final SftpSessionExpiryCleanup cleanupTask = new SftpSessionExpiryCleanup();
|
private final SftpSessionExpiryCleanup cleanupTask = new SftpSessionExpiryCleanup();
|
||||||
|
|
||||||
public static class SftpSessionExpiryCleanup {
|
public static class SftpSessionExpiryCleanup {
|
||||||
@@ -441,4 +729,262 @@ public class SftpController {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static class TransferTaskStatus {
|
||||||
|
private final String taskId;
|
||||||
|
private final Long userId;
|
||||||
|
private final Long sourceConnectionId;
|
||||||
|
private final Long targetConnectionId;
|
||||||
|
private final String sourcePath;
|
||||||
|
private final String targetPath;
|
||||||
|
private final long createdAt;
|
||||||
|
private volatile String status;
|
||||||
|
private volatile String error;
|
||||||
|
private volatile long startedAt;
|
||||||
|
private volatile long finishedAt;
|
||||||
|
private final AtomicLong totalBytes;
|
||||||
|
private final AtomicLong transferredBytes;
|
||||||
|
private volatile Future<?> future;
|
||||||
|
private volatile SftpController controller;
|
||||||
|
|
||||||
|
public TransferTaskStatus(String taskId,
|
||||||
|
Long userId,
|
||||||
|
Long sourceConnectionId,
|
||||||
|
Long targetConnectionId,
|
||||||
|
String sourcePath,
|
||||||
|
String targetPath) {
|
||||||
|
this.taskId = taskId;
|
||||||
|
this.userId = userId;
|
||||||
|
this.sourceConnectionId = sourceConnectionId;
|
||||||
|
this.targetConnectionId = targetConnectionId;
|
||||||
|
this.sourcePath = sourcePath;
|
||||||
|
this.targetPath = targetPath;
|
||||||
|
this.createdAt = System.currentTimeMillis();
|
||||||
|
this.status = "queued";
|
||||||
|
this.totalBytes = new AtomicLong(0);
|
||||||
|
this.transferredBytes = new AtomicLong(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTaskId() {
|
||||||
|
return taskId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setController(SftpController controller) {
|
||||||
|
this.controller = controller;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFuture(Future<?> future) {
|
||||||
|
this.future = future;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStatus(String status) {
|
||||||
|
this.status = status;
|
||||||
|
if ("running".equals(status) && startedAt == 0) {
|
||||||
|
startedAt = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
notifyProgress();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setProgress(long transferred, long total) {
|
||||||
|
if (startedAt == 0) {
|
||||||
|
startedAt = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
transferredBytes.set(Math.max(0, transferred));
|
||||||
|
totalBytes.set(Math.max(0, total));
|
||||||
|
notifyProgress();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void markSuccess() {
|
||||||
|
long total = totalBytes.get();
|
||||||
|
if (total > 0) {
|
||||||
|
transferredBytes.set(total);
|
||||||
|
}
|
||||||
|
status = "success";
|
||||||
|
finishedAt = System.currentTimeMillis();
|
||||||
|
notifyProgress();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void markError(String message) {
|
||||||
|
status = "error";
|
||||||
|
error = message;
|
||||||
|
finishedAt = System.currentTimeMillis();
|
||||||
|
notifyProgress();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void markCancelled() {
|
||||||
|
status = "cancelled";
|
||||||
|
finishedAt = System.currentTimeMillis();
|
||||||
|
notifyProgress();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void notifyProgress() {
|
||||||
|
if (controller != null) {
|
||||||
|
String taskKey = controller.transferTaskKey(userId, taskId);
|
||||||
|
controller.broadcastProgress(taskKey, toResponse());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean cancel() {
|
||||||
|
if (!"queued".equals(status) && !"running".equals(status)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Future<?> currentFuture = future;
|
||||||
|
if (currentFuture != null) {
|
||||||
|
currentFuture.cancel(true);
|
||||||
|
}
|
||||||
|
markCancelled();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> toResponse() {
|
||||||
|
long total = totalBytes.get();
|
||||||
|
long transferred = transferredBytes.get();
|
||||||
|
int progress = total > 0 ? (int) Math.min(100, Math.round((transferred * 100.0) / total)) :
|
||||||
|
(("success".equals(status) || "error".equals(status) || "cancelled".equals(status)) ? 100 : 0);
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("taskId", taskId);
|
||||||
|
result.put("userId", userId);
|
||||||
|
result.put("sourceConnectionId", sourceConnectionId);
|
||||||
|
result.put("targetConnectionId", targetConnectionId);
|
||||||
|
result.put("sourcePath", sourcePath);
|
||||||
|
result.put("targetPath", targetPath);
|
||||||
|
result.put("status", status);
|
||||||
|
result.put("progress", progress);
|
||||||
|
result.put("transferredBytes", transferred);
|
||||||
|
result.put("totalBytes", total);
|
||||||
|
result.put("createdAt", createdAt);
|
||||||
|
result.put("startedAt", startedAt);
|
||||||
|
result.put("finishedAt", finishedAt);
|
||||||
|
if (error != null && !error.isEmpty()) {
|
||||||
|
result.put("error", error);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isExpired(long now, long timeoutMillis) {
|
||||||
|
if ("queued".equals(status) || "running".equals(status)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
long endTime = finishedAt > 0 ? finishedAt : createdAt;
|
||||||
|
return now - endTime > timeoutMillis;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class UploadTaskStatus {
|
||||||
|
private final String taskId;
|
||||||
|
private final Long userId;
|
||||||
|
private final Long connectionId;
|
||||||
|
private final String path;
|
||||||
|
private final String filename;
|
||||||
|
private final long fileSize;
|
||||||
|
private final long createdAt;
|
||||||
|
private volatile String status;
|
||||||
|
private volatile String error;
|
||||||
|
private volatile long startedAt;
|
||||||
|
private volatile long finishedAt;
|
||||||
|
private final AtomicLong totalBytes;
|
||||||
|
private final AtomicLong transferredBytes;
|
||||||
|
private volatile Future<?> future;
|
||||||
|
private volatile SftpController controller;
|
||||||
|
|
||||||
|
public UploadTaskStatus(String taskId, Long userId, Long connectionId,
|
||||||
|
String path, String filename, long fileSize) {
|
||||||
|
this.taskId = taskId;
|
||||||
|
this.userId = userId;
|
||||||
|
this.connectionId = connectionId;
|
||||||
|
this.path = path;
|
||||||
|
this.filename = filename;
|
||||||
|
this.fileSize = fileSize;
|
||||||
|
this.createdAt = System.currentTimeMillis();
|
||||||
|
this.status = "queued";
|
||||||
|
this.totalBytes = new AtomicLong(fileSize);
|
||||||
|
this.transferredBytes = new AtomicLong(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getTotalBytes() {
|
||||||
|
return totalBytes.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setController(SftpController controller) {
|
||||||
|
this.controller = controller;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFuture(Future<?> future) {
|
||||||
|
this.future = future;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStatus(String status) {
|
||||||
|
this.status = status;
|
||||||
|
if ("running".equals(status) && startedAt == 0) {
|
||||||
|
startedAt = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
notifyProgress();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setProgress(long transferred, long total) {
|
||||||
|
if (startedAt == 0) {
|
||||||
|
startedAt = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
transferredBytes.set(Math.max(0, transferred));
|
||||||
|
if (total > 0) {
|
||||||
|
totalBytes.set(Math.max(0, total));
|
||||||
|
}
|
||||||
|
notifyProgress();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void markSuccess() {
|
||||||
|
long total = totalBytes.get();
|
||||||
|
if (total > 0) {
|
||||||
|
transferredBytes.set(total);
|
||||||
|
}
|
||||||
|
status = "success";
|
||||||
|
finishedAt = System.currentTimeMillis();
|
||||||
|
notifyProgress();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void markError(String message) {
|
||||||
|
status = "error";
|
||||||
|
error = message;
|
||||||
|
finishedAt = System.currentTimeMillis();
|
||||||
|
notifyProgress();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void notifyProgress() {
|
||||||
|
if (controller != null) {
|
||||||
|
String taskKey = controller.uploadTaskKey(userId, taskId);
|
||||||
|
controller.broadcastProgress(taskKey, toResponse());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> toResponse() {
|
||||||
|
long total = totalBytes.get();
|
||||||
|
long transferred = transferredBytes.get();
|
||||||
|
int progress = total > 0 ? (int) Math.min(100, Math.round((transferred * 100.0) / total)) :
|
||||||
|
(("success".equals(status) || "error".equals(status)) ? 100 : 0);
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("taskId", taskId);
|
||||||
|
result.put("status", status);
|
||||||
|
result.put("progress", progress);
|
||||||
|
result.put("transferredBytes", transferred);
|
||||||
|
result.put("totalBytes", total);
|
||||||
|
result.put("filename", filename);
|
||||||
|
result.put("createdAt", createdAt);
|
||||||
|
result.put("startedAt", startedAt);
|
||||||
|
result.put("finishedAt", finishedAt);
|
||||||
|
if (error != null && !error.isEmpty()) {
|
||||||
|
result.put("error", error);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isExpired(long now, long timeoutMillis) {
|
||||||
|
if ("queued".equals(status) || "running".equals(status)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
long endTime = finishedAt > 0 ? finishedAt : createdAt;
|
||||||
|
return now - endTime > timeoutMillis;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,8 +52,9 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
|
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
|
||||||
return bearerToken.substring(7);
|
return bearerToken.substring(7);
|
||||||
}
|
}
|
||||||
// WebSocket handshake sends token as query param
|
// WebSocket handshake and SSE endpoints send token as query param
|
||||||
if (request.getRequestURI() != null && request.getRequestURI().startsWith("/ws/")) {
|
String uri = request.getRequestURI();
|
||||||
|
if (uri != null && (uri.startsWith("/ws/") || uri.contains("/progress"))) {
|
||||||
String token = request.getParameter("token");
|
String token = request.getParameter("token");
|
||||||
if (StringUtils.hasText(token)) {
|
if (StringUtils.hasText(token)) {
|
||||||
return token;
|
return token;
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ package com.sshmanager.service;
|
|||||||
import com.jcraft.jsch.ChannelSftp;
|
import com.jcraft.jsch.ChannelSftp;
|
||||||
import com.jcraft.jsch.JSch;
|
import com.jcraft.jsch.JSch;
|
||||||
import com.jcraft.jsch.Session;
|
import com.jcraft.jsch.Session;
|
||||||
|
import com.jcraft.jsch.SftpATTRS;
|
||||||
import com.jcraft.jsch.SftpException;
|
import com.jcraft.jsch.SftpException;
|
||||||
|
import com.jcraft.jsch.SftpProgressMonitor;
|
||||||
import com.sshmanager.entity.Connection;
|
import com.sshmanager.entity.Connection;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@@ -15,12 +17,10 @@ import java.nio.charset.StandardCharsets;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Vector;
|
import java.util.Vector;
|
||||||
import java.util.concurrent.ExecutionException;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.Future;
|
import java.util.concurrent.Future;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
import java.util.concurrent.TimeoutException;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class SftpService {
|
public class SftpService {
|
||||||
@@ -104,6 +104,12 @@ public class SftpService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public interface TransferProgressListener {
|
||||||
|
void onStart(long totalBytes);
|
||||||
|
|
||||||
|
void onProgress(long transferredBytes, long totalBytes);
|
||||||
|
}
|
||||||
|
|
||||||
public List<FileInfo> listFiles(SftpSession sftpSession, String path) throws Exception {
|
public List<FileInfo> listFiles(SftpSession sftpSession, String path) throws Exception {
|
||||||
String listPath = (path == null || path.trim().isEmpty()) ? "." : path.trim();
|
String listPath = (path == null || path.trim().isEmpty()) ? "." : path.trim();
|
||||||
try {
|
try {
|
||||||
@@ -168,6 +174,30 @@ public class SftpService {
|
|||||||
sftpSession.getChannel().put(in, remotePath);
|
sftpSession.getChannel().put(in, remotePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void upload(SftpSession sftpSession, String remotePath, InputStream in, TransferProgressListener progressListener) throws Exception {
|
||||||
|
sftpSession.getChannel().put(in, remotePath, new SftpProgressMonitor() {
|
||||||
|
@Override
|
||||||
|
public void init(int op, String src, String dest, long max) {
|
||||||
|
if (progressListener != null) {
|
||||||
|
progressListener.onStart(max);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean count(long count) {
|
||||||
|
if (progressListener != null) {
|
||||||
|
progressListener.onProgress(count, 0);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void end() {
|
||||||
|
// Progress listener will be notified by controller
|
||||||
|
}
|
||||||
|
}, ChannelSftp.OVERWRITE);
|
||||||
|
}
|
||||||
|
|
||||||
public void delete(SftpSession sftpSession, String remotePath, boolean isDir) throws Exception {
|
public void delete(SftpSession sftpSession, String remotePath, boolean isDir) throws Exception {
|
||||||
if (isDir) {
|
if (isDir) {
|
||||||
sftpSession.getChannel().rmdir(remotePath);
|
sftpSession.getChannel().rmdir(remotePath);
|
||||||
@@ -198,26 +228,73 @@ public class SftpService {
|
|||||||
*/
|
*/
|
||||||
public void transferRemote(SftpSession source, String sourcePath, SftpSession target, String targetPath)
|
public void transferRemote(SftpSession source, String sourcePath, SftpSession target, String targetPath)
|
||||||
throws Exception {
|
throws Exception {
|
||||||
if (source.getChannel().stat(sourcePath).isDir()) {
|
transferRemote(source, sourcePath, target, targetPath, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void transferRemote(SftpSession source,
|
||||||
|
String sourcePath,
|
||||||
|
SftpSession target,
|
||||||
|
String targetPath,
|
||||||
|
TransferProgressListener progressListener) throws Exception {
|
||||||
|
SftpATTRS attrs = source.getChannel().stat(sourcePath);
|
||||||
|
if (attrs.isDir()) {
|
||||||
throw new IllegalArgumentException("Source path is a directory; only single file transfer is supported");
|
throw new IllegalArgumentException("Source path is a directory; only single file transfer is supported");
|
||||||
}
|
}
|
||||||
|
final long totalBytes = attrs.getSize();
|
||||||
final int pipeBufferSize = 65536;
|
final int pipeBufferSize = 65536;
|
||||||
PipedOutputStream pos = new PipedOutputStream();
|
PipedOutputStream pos = new PipedOutputStream();
|
||||||
PipedInputStream pis = new PipedInputStream(pos, pipeBufferSize);
|
PipedInputStream pis = new PipedInputStream(pos, pipeBufferSize);
|
||||||
|
AtomicLong transferredBytes = new AtomicLong(0);
|
||||||
|
|
||||||
|
if (progressListener != null) {
|
||||||
|
progressListener.onStart(totalBytes);
|
||||||
|
}
|
||||||
|
|
||||||
Future<?> putFuture = executorService.submit(() -> {
|
Future<?> putFuture = executorService.submit(() -> {
|
||||||
try {
|
try {
|
||||||
target.getChannel().put(pis, targetPath);
|
target.getChannel().put(pis, targetPath, new SftpProgressMonitor() {
|
||||||
|
@Override
|
||||||
|
public void init(int op, String src, String dest, long max) {
|
||||||
|
if (progressListener != null) {
|
||||||
|
progressListener.onStart(totalBytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean count(long count) {
|
||||||
|
long current = transferredBytes.addAndGet(count);
|
||||||
|
if (progressListener != null) {
|
||||||
|
progressListener.onProgress(current, totalBytes);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void end() {
|
||||||
|
if (progressListener != null) {
|
||||||
|
progressListener.onProgress(totalBytes, totalBytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, ChannelSftp.OVERWRITE);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
try {
|
||||||
source.getChannel().get(sourcePath, pos);
|
source.getChannel().get(sourcePath, pos);
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
pos.close();
|
pos.close();
|
||||||
putFuture.get(5, TimeUnit.MINUTES);
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
putFuture.get();
|
||||||
|
} finally {
|
||||||
try {
|
try {
|
||||||
pis.close();
|
pis.close();
|
||||||
} catch (Exception ignored) {
|
} catch (Exception ignored) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
# SSH 管理器设计系统
|
|
||||||
|
|
||||||
## 风格
|
|
||||||
|
|
||||||
- **产品类型**:管理后台 / 开发工具仪表盘
|
|
||||||
- **主题**:深色、专业、终端风格
|
|
||||||
- **布局**:侧边栏 + 主内容区
|
|
||||||
|
|
||||||
## 色彩
|
|
||||||
|
|
||||||
- 背景:slate-900 (#0f172a)、slate-800
|
|
||||||
- 表面:slate-800、slate-700
|
|
||||||
- 主文字:slate-100 (#f1f5f9)
|
|
||||||
- 次要文字:slate-400
|
|
||||||
- 强调(成功/连接):emerald-500、cyan-500
|
|
||||||
- 边框:slate-600、slate-700
|
|
||||||
|
|
||||||
## 字体
|
|
||||||
|
|
||||||
- 字体:Inter 或 system-ui
|
|
||||||
- 正文:最小 16px,行高 1.5
|
|
||||||
|
|
||||||
## 图标
|
|
||||||
|
|
||||||
- 仅使用 Lucide 图标,不使用 emoji
|
|
||||||
- 尺寸:统一 20px 或 24px
|
|
||||||
|
|
||||||
## 交互
|
|
||||||
|
|
||||||
- 所有可点击元素使用 cursor-pointer
|
|
||||||
- transition-colors duration-200
|
|
||||||
- 最小触控区域 44×44px
|
|
||||||
|
|
||||||
## 无障碍
|
|
||||||
|
|
||||||
- 对比度 4.5:1
|
|
||||||
- 可见焦点环
|
|
||||||
- 仅图标按钮需设置 aria-label
|
|
||||||
43
docs/design-system/MASTER.md
Normal file
43
docs/design-system/MASTER.md
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
# SSH Manager Transfer Console - Design System (Master)
|
||||||
|
|
||||||
|
Goal: a fast, reliable, ops-style UI for moving data across many hosts.
|
||||||
|
|
||||||
|
Design principles
|
||||||
|
- Transfer-first: primary surface is "plans / queue / progress"; connections are supporting data.
|
||||||
|
- Dense but calm: show more information without visual noise; consistent rhythm and spacing.
|
||||||
|
- Failure is actionable: errors are specific, local to the job, and keep context.
|
||||||
|
- Keyboard-friendly: visible focus rings, logical tab order, no hover-only actions.
|
||||||
|
|
||||||
|
Color and surfaces (dark-first)
|
||||||
|
- Background: deep slate with subtle gradient + faint grid/noise.
|
||||||
|
- Surfaces: layered cards (solid + slight transparency) with visible borders.
|
||||||
|
- Accent: cyan for primary actions and progress.
|
||||||
|
- Status:
|
||||||
|
- Success: green
|
||||||
|
- Warning: amber
|
||||||
|
- Danger: red
|
||||||
|
|
||||||
|
Typography
|
||||||
|
- Headings: IBM Plex Sans (600-700)
|
||||||
|
- Body: IBM Plex Sans (400-500)
|
||||||
|
- Mono (paths, hostnames, commands): IBM Plex Mono
|
||||||
|
|
||||||
|
Spacing and layout
|
||||||
|
- App shell: left rail (nav) + main content; content uses max width on desktop.
|
||||||
|
- Cards: 12-16px padding on mobile, 16-20px on desktop.
|
||||||
|
- Touch targets: >= 44px for buttons / list rows.
|
||||||
|
|
||||||
|
Interaction
|
||||||
|
- Buttons: disable during async; show inline spinner + label change ("Starting…").
|
||||||
|
- Loading: skeleton for lists; avoid layout jump.
|
||||||
|
- Motion: 150-250ms transitions; respect prefers-reduced-motion.
|
||||||
|
|
||||||
|
Accessibility
|
||||||
|
- Contrast: normal text >= 4.5:1.
|
||||||
|
- Focus: always visible focus ring on interactive elements.
|
||||||
|
- Icon-only buttons must have aria-label.
|
||||||
|
|
||||||
|
Transfer UX patterns
|
||||||
|
- "Plan" = input + targets + options; "Run" produces jobs in a queue.
|
||||||
|
- Queue rows show: source, targets count, status, progress, started/finished, retry.
|
||||||
|
- Progress: per-target progress when available (XHR upload), otherwise discrete states.
|
||||||
@@ -4,7 +4,13 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>SSH 管理器</title>
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
<link
|
||||||
|
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600;700&display=swap"
|
||||||
|
rel="stylesheet"
|
||||||
|
/>
|
||||||
|
<title>SSH 传输控制台</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|||||||
@@ -7,6 +7,18 @@ export interface SftpFileInfo {
|
|||||||
mtime: number
|
mtime: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface RemoteTransferTask {
|
||||||
|
taskId: string
|
||||||
|
status: 'queued' | 'running' | 'success' | 'error' | 'cancelled'
|
||||||
|
progress: number
|
||||||
|
transferredBytes: number
|
||||||
|
totalBytes: number
|
||||||
|
error?: string
|
||||||
|
createdAt: number
|
||||||
|
startedAt: number
|
||||||
|
finishedAt: number
|
||||||
|
}
|
||||||
|
|
||||||
export function listFiles(connectionId: number, path: string) {
|
export function listFiles(connectionId: number, path: string) {
|
||||||
return client.get<SftpFileInfo[]>('/sftp/list', {
|
return client.get<SftpFileInfo[]>('/sftp/list', {
|
||||||
params: { connectionId, path: path || '.' },
|
params: { connectionId, path: path || '.' },
|
||||||
@@ -47,49 +59,63 @@ export function uploadFileWithProgress(connectionId: number, path: string, file:
|
|||||||
xhr.open('POST', url)
|
xhr.open('POST', url)
|
||||||
xhr.setRequestHeader('Authorization', `Bearer ${token}`)
|
xhr.setRequestHeader('Authorization', `Bearer ${token}`)
|
||||||
|
|
||||||
|
// Create a wrapper object to hold the progress callback
|
||||||
|
const wrapper = { onProgress: undefined as ((percent: number) => void) | undefined }
|
||||||
|
|
||||||
|
// Allow caller to attach handlers after this function returns.
|
||||||
xhr.upload.onprogress = (event) => {
|
xhr.upload.onprogress = (event) => {
|
||||||
if (event.lengthComputable) {
|
console.log('[Upload Progress] event fired:', { lengthComputable: event.lengthComputable, loaded: event.loaded, total: event.total })
|
||||||
|
if (!event.lengthComputable) return
|
||||||
const percent = Math.round((event.loaded / event.total) * 100)
|
const percent = Math.round((event.loaded / event.total) * 100)
|
||||||
if ((xhr as any).onProgress) {
|
console.log('[Upload Progress] percent:', percent, 'hasCallback:', !!wrapper.onProgress)
|
||||||
(xhr as any).onProgress(percent)
|
if (wrapper.onProgress) wrapper.onProgress(percent)
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
xhr.onload = () => {
|
// Defer send so callers can attach onload/onerror/onProgress safely.
|
||||||
if (xhr.status >= 200 && xhr.status < 300) {
|
setTimeout(() => {
|
||||||
try {
|
try {
|
||||||
const responseJson = JSON.parse(xhr.responseText) as { message: string }
|
|
||||||
;(xhr as any).resolve(responseJson)
|
|
||||||
} catch {
|
|
||||||
;(xhr as any).resolve({ message: 'Uploaded' })
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
const responseJson = JSON.parse(xhr.responseText) as { error?: string }
|
|
||||||
;(xhr as any).reject(new Error(responseJson.error || `Upload failed: ${xhr.status}`))
|
|
||||||
} catch {
|
|
||||||
;(xhr as any).reject(new Error(`Upload failed: ${xhr.status}`))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
xhr.onerror = () => {
|
|
||||||
;(xhr as any).reject(new Error('Network error'))
|
|
||||||
}
|
|
||||||
|
|
||||||
xhr.send(form)
|
xhr.send(form)
|
||||||
return xhr as XMLHttpRequest & { onProgress?: (percent: number) => void; resolve?: (value: any) => void; reject?: (reason?: any) => void }
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}, 0)
|
||||||
|
|
||||||
|
// Return XHR with a setter that updates the wrapper
|
||||||
|
const result = xhr as XMLHttpRequest & { onProgress?: (percent: number) => void }
|
||||||
|
Object.defineProperty(result, 'onProgress', {
|
||||||
|
get: () => wrapper.onProgress,
|
||||||
|
set: (fn) => { wrapper.onProgress = fn },
|
||||||
|
enumerable: true,
|
||||||
|
configurable: true
|
||||||
|
})
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
export function uploadFile(connectionId: number, path: string, file: File) {
|
export function uploadFile(connectionId: number, path: string, file: File) {
|
||||||
const form = new FormData()
|
const form = new FormData()
|
||||||
form.append('file', file, file.name)
|
form.append('file', file, file.name)
|
||||||
return client.post('/sftp/upload', form, {
|
return client.post<{ taskId: string; message: string }>('/sftp/upload', form, {
|
||||||
params: { connectionId, path },
|
params: { connectionId, path },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface UploadTask {
|
||||||
|
taskId: string
|
||||||
|
status: 'queued' | 'running' | 'success' | 'error'
|
||||||
|
progress: number
|
||||||
|
transferredBytes: number
|
||||||
|
totalBytes: number
|
||||||
|
filename: string
|
||||||
|
error?: string
|
||||||
|
createdAt: number
|
||||||
|
startedAt: number
|
||||||
|
finishedAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getUploadTask(taskId: string) {
|
||||||
|
return client.get<UploadTask>(`/sftp/upload/tasks/${encodeURIComponent(taskId)}`)
|
||||||
|
}
|
||||||
|
|
||||||
export function deleteFile(connectionId: number, path: string, directory: boolean) {
|
export function deleteFile(connectionId: number, path: string, directory: boolean) {
|
||||||
return client.delete('/sftp/delete', {
|
return client.delete('/sftp/delete', {
|
||||||
params: { connectionId, path, directory },
|
params: { connectionId, path, directory },
|
||||||
@@ -123,3 +149,78 @@ export function transferRemote(
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function createRemoteTransferTask(
|
||||||
|
sourceConnectionId: number,
|
||||||
|
sourcePath: string,
|
||||||
|
targetConnectionId: number,
|
||||||
|
targetPath: string
|
||||||
|
) {
|
||||||
|
return client.post<RemoteTransferTask>('/sftp/transfer-remote/tasks', null, {
|
||||||
|
params: {
|
||||||
|
sourceConnectionId,
|
||||||
|
sourcePath,
|
||||||
|
targetConnectionId,
|
||||||
|
targetPath,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRemoteTransferTask(taskId: string) {
|
||||||
|
return client.get<RemoteTransferTask>(`/sftp/transfer-remote/tasks/${encodeURIComponent(taskId)}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeRemoteTransferProgress(taskId: string, onProgress: (task: RemoteTransferTask) => void): () => void {
|
||||||
|
const token = localStorage.getItem('token')
|
||||||
|
const url = `/api/sftp/transfer-remote/tasks/${encodeURIComponent(taskId)}/progress`
|
||||||
|
const eventSource = new EventSource(`${url}?token=${encodeURIComponent(token || '')}`)
|
||||||
|
|
||||||
|
eventSource.addEventListener('progress', (event) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(event.data)
|
||||||
|
console.log('[SSE] Received progress event:', data)
|
||||||
|
onProgress(data)
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to parse SSE progress data:', e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
eventSource.addEventListener('error', (event) => {
|
||||||
|
console.error('SSE connection error:', event)
|
||||||
|
eventSource.close()
|
||||||
|
})
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
eventSource.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeUploadProgress(taskId: string, onProgress: (task: UploadTask) => void): () => void {
|
||||||
|
const token = localStorage.getItem('token')
|
||||||
|
const url = `/api/sftp/upload/tasks/${encodeURIComponent(taskId)}/progress`
|
||||||
|
const eventSource = new EventSource(`${url}?token=${encodeURIComponent(token || '')}`)
|
||||||
|
|
||||||
|
eventSource.addEventListener('progress', (event) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(event.data)
|
||||||
|
onProgress(data)
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to parse SSE progress data:', e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
eventSource.addEventListener('error', (event) => {
|
||||||
|
console.error('SSE connection error:', event)
|
||||||
|
eventSource.close()
|
||||||
|
})
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
eventSource.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cancelRemoteTransferTask(taskId: string) {
|
||||||
|
return client.delete<RemoteTransferTask & { cancelRequested: boolean; message?: string }>(
|
||||||
|
`/sftp/transfer-remote/tasks/${encodeURIComponent(taskId)}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
222
frontend/src/components/SftpFilePickerModal.vue
Normal file
222
frontend/src/components/SftpFilePickerModal.vue
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
|
|
||||||
|
import * as sftpApi from '../api/sftp'
|
||||||
|
import type { SftpFileInfo } from '../api/sftp'
|
||||||
|
import { X, FolderOpen, File, ChevronRight, RefreshCw, Eye, EyeOff } from 'lucide-vue-next'
|
||||||
|
|
||||||
|
const props = defineProps<{ open: boolean; connectionId: number | null }>()
|
||||||
|
const emit = defineEmits<{
|
||||||
|
(e: 'close'): void
|
||||||
|
(e: 'select', path: string): void
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const currentPath = ref('.')
|
||||||
|
const pathParts = ref<string[]>([])
|
||||||
|
const files = ref<SftpFileInfo[]>([])
|
||||||
|
const loading = ref(false)
|
||||||
|
const error = ref('')
|
||||||
|
|
||||||
|
const showHiddenFiles = ref(false)
|
||||||
|
const searchQuery = ref('')
|
||||||
|
let searchDebounceTimer = 0
|
||||||
|
const filteredFiles = ref<SftpFileInfo[]>([])
|
||||||
|
|
||||||
|
const canInteract = computed(() => props.open && props.connectionId != null)
|
||||||
|
|
||||||
|
function applyFileFilters() {
|
||||||
|
const q = searchQuery.value.trim().toLowerCase()
|
||||||
|
const base = showHiddenFiles.value ? files.value : files.value.filter((f) => !f.name.startsWith('.'))
|
||||||
|
filteredFiles.value = q ? base.filter((f) => f.name.toLowerCase().includes(q)) : base
|
||||||
|
}
|
||||||
|
|
||||||
|
watch([searchQuery, showHiddenFiles, files], () => {
|
||||||
|
clearTimeout(searchDebounceTimer)
|
||||||
|
searchDebounceTimer = window.setTimeout(() => {
|
||||||
|
applyFileFilters()
|
||||||
|
}, 300)
|
||||||
|
}, { immediate: true })
|
||||||
|
|
||||||
|
async function initPath() {
|
||||||
|
if (!canInteract.value || props.connectionId == null) return
|
||||||
|
error.value = ''
|
||||||
|
try {
|
||||||
|
const res = await sftpApi.getPwd(props.connectionId)
|
||||||
|
const p = res.data.path || '/'
|
||||||
|
currentPath.value = p === '/' ? '/' : p
|
||||||
|
pathParts.value = p === '/' ? [''] : p.split('/').filter(Boolean)
|
||||||
|
} catch (e: unknown) {
|
||||||
|
currentPath.value = '.'
|
||||||
|
pathParts.value = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
if (!canInteract.value || props.connectionId == null) return
|
||||||
|
loading.value = true
|
||||||
|
error.value = ''
|
||||||
|
try {
|
||||||
|
const res = await sftpApi.listFiles(props.connectionId, currentPath.value)
|
||||||
|
files.value = res.data
|
||||||
|
.slice()
|
||||||
|
.sort((a, b) => {
|
||||||
|
if (a.directory !== b.directory) return a.directory ? -1 : 1
|
||||||
|
return a.name.localeCompare(b.name)
|
||||||
|
})
|
||||||
|
} catch (e: unknown) {
|
||||||
|
const err = e as { response?: { data?: { error?: string } } }
|
||||||
|
error.value = err?.response?.data?.error ?? '获取文件列表失败'
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function navigateToDir(name: string) {
|
||||||
|
if (loading.value) return
|
||||||
|
const base = currentPath.value === '.' || currentPath.value === '' ? '' : currentPath.value
|
||||||
|
currentPath.value = base ? (base.endsWith('/') ? base + name : base + '/' + name) : name
|
||||||
|
pathParts.value = currentPath.value === '/' ? [''] : currentPath.value.split('/').filter(Boolean)
|
||||||
|
load()
|
||||||
|
}
|
||||||
|
|
||||||
|
function navigateToIndex(i: number) {
|
||||||
|
if (loading.value) return
|
||||||
|
if (i < 0) {
|
||||||
|
currentPath.value = '.'
|
||||||
|
} else {
|
||||||
|
currentPath.value = pathParts.value.length ? '/' + pathParts.value.slice(0, i + 1).join('/') : '/'
|
||||||
|
}
|
||||||
|
pathParts.value = currentPath.value === '/' ? [''] : currentPath.value.split('/').filter(Boolean)
|
||||||
|
load()
|
||||||
|
}
|
||||||
|
|
||||||
|
function filePath(file: SftpFileInfo) {
|
||||||
|
const base = currentPath.value === '.' || !currentPath.value ? '' : currentPath.value
|
||||||
|
return base ? base.replace(/\/$/, '') + '/' + file.name : file.name
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClick(file: SftpFileInfo) {
|
||||||
|
if (file.directory) {
|
||||||
|
navigateToDir(file.name)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
emit('select', filePath(file))
|
||||||
|
emit('close')
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => [props.open, props.connectionId] as const,
|
||||||
|
async ([open]) => {
|
||||||
|
if (!open) return
|
||||||
|
await initPath()
|
||||||
|
await load()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function onKeyDown(e: KeyboardEvent) {
|
||||||
|
if (!props.open) return
|
||||||
|
if (e.key === 'Escape') emit('close')
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => window.addEventListener('keydown', onKeyDown))
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
window.removeEventListener('keydown', onKeyDown)
|
||||||
|
clearTimeout(searchDebounceTimer)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Teleport to="body">
|
||||||
|
<div v-if="open" class="fixed inset-0 z-50 bg-black/60 p-4 flex items-center justify-center" role="dialog" aria-modal="true">
|
||||||
|
<div class="w-full max-w-3xl rounded-2xl border border-slate-700 bg-slate-900/70 backdrop-blur shadow-2xl overflow-hidden">
|
||||||
|
<div class="flex items-center justify-between px-4 py-3 border-b border-slate-700">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<h3 class="text-slate-100 font-semibold truncate">选择源文件</h3>
|
||||||
|
<p class="text-xs text-slate-400 truncate">双击文件不需要,单击即选择</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
@click="load"
|
||||||
|
:disabled="loading || !canInteract"
|
||||||
|
class="min-h-[44px] px-3 rounded-lg border border-slate-700 bg-slate-800/60 text-slate-200 hover:bg-slate-800 disabled:opacity-50 cursor-pointer transition-colors"
|
||||||
|
aria-label="刷新"
|
||||||
|
>
|
||||||
|
<span class="inline-flex items-center gap-2">
|
||||||
|
<RefreshCw class="w-4 h-4" :class="{ 'animate-spin': loading }" aria-hidden="true" />
|
||||||
|
刷新
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
@click="emit('close')"
|
||||||
|
class="min-h-[44px] w-11 grid place-items-center rounded-lg border border-slate-700 bg-slate-800/60 text-slate-200 hover:bg-slate-800 cursor-pointer transition-colors"
|
||||||
|
aria-label="关闭"
|
||||||
|
>
|
||||||
|
<X class="w-5 h-5" aria-hidden="true" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="px-4 py-3 border-b border-slate-700 bg-slate-900/40">
|
||||||
|
<nav class="flex items-center gap-1 text-sm text-slate-400 min-w-0">
|
||||||
|
<button
|
||||||
|
@click="navigateToIndex(-1)"
|
||||||
|
class="px-2 py-1 rounded hover:bg-slate-800 hover:text-slate-100 transition-colors cursor-pointer truncate"
|
||||||
|
>
|
||||||
|
/
|
||||||
|
</button>
|
||||||
|
<template v-for="(part, i) in pathParts" :key="i">
|
||||||
|
<ChevronRight class="w-4 h-4 flex-shrink-0 text-slate-600" aria-hidden="true" />
|
||||||
|
<button
|
||||||
|
@click="navigateToIndex(i)"
|
||||||
|
class="px-2 py-1 rounded hover:bg-slate-800 hover:text-slate-100 transition-colors cursor-pointer truncate max-w-[140px]"
|
||||||
|
>
|
||||||
|
{{ part || '/' }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
</nav>
|
||||||
|
<div class="mt-3 flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
v-model="searchQuery"
|
||||||
|
type="text"
|
||||||
|
class="flex-1 rounded-lg border border-slate-600 bg-slate-900/30 px-3 py-2 text-sm text-slate-100 placeholder-slate-500 focus:border-cyan-500 focus:outline-none focus:ring-1 focus:ring-cyan-500"
|
||||||
|
placeholder="搜索文件..."
|
||||||
|
aria-label="搜索文件"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
@click="showHiddenFiles = !showHiddenFiles"
|
||||||
|
class="min-h-[44px] p-2 rounded-lg text-slate-400 hover:bg-slate-700 hover:text-slate-100 transition-colors cursor-pointer"
|
||||||
|
:aria-label="showHiddenFiles ? '隐藏隐藏文件' : '显示隐藏文件'"
|
||||||
|
:title="showHiddenFiles ? '隐藏隐藏文件' : '显示隐藏文件'"
|
||||||
|
>
|
||||||
|
<component :is="showHiddenFiles ? EyeOff : Eye" class="w-4 h-4" aria-hidden="true" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p v-if="error" class="mt-2 text-sm text-red-400">{{ error }}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="max-h-[60vh] overflow-auto divide-y divide-slate-800">
|
||||||
|
<button
|
||||||
|
v-for="file in filteredFiles"
|
||||||
|
:key="file.name"
|
||||||
|
@click="handleClick(file)"
|
||||||
|
class="w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-slate-800/40 transition-colors cursor-pointer min-h-[44px]"
|
||||||
|
:aria-label="file.directory ? '打开目录' : '选择文件'"
|
||||||
|
>
|
||||||
|
<component
|
||||||
|
:is="file.directory ? FolderOpen : File"
|
||||||
|
class="w-5 h-5 flex-shrink-0"
|
||||||
|
:class="file.directory ? 'text-cyan-300' : 'text-slate-300'"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<span class="flex-1 min-w-0 truncate text-slate-100">{{ file.name }}</span>
|
||||||
|
<span v-if="!file.directory" class="text-xs text-slate-500">{{ Math.round(file.size / 1024) }} KB</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div v-if="filteredFiles.length === 0 && !loading" class="px-4 py-10 text-center text-slate-500">
|
||||||
|
{{ files.length === 0 ? '空目录' : (searchQuery.trim() ? '未找到匹配文件' : '无可见文件(已隐藏文件)') }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
|
</template>
|
||||||
@@ -3,7 +3,7 @@ import { ref } from 'vue'
|
|||||||
import { RouterLink, useRoute } from 'vue-router'
|
import { RouterLink, useRoute } from 'vue-router'
|
||||||
import { useAuthStore } from '../stores/auth'
|
import { useAuthStore } from '../stores/auth'
|
||||||
import { useConnectionsStore } from '../stores/connections'
|
import { useConnectionsStore } from '../stores/connections'
|
||||||
import { Server, LogOut, Menu, X } from 'lucide-vue-next'
|
import { ArrowLeftRight, Server, LogOut, Menu, X } from 'lucide-vue-next'
|
||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const authStore = useAuthStore()
|
const authStore = useAuthStore()
|
||||||
@@ -35,10 +35,20 @@ function closeSidebar() {
|
|||||||
]"
|
]"
|
||||||
>
|
>
|
||||||
<div class="p-4 border-b border-slate-700">
|
<div class="p-4 border-b border-slate-700">
|
||||||
<h1 class="text-lg font-semibold text-slate-100">SSH 管理器</h1>
|
<h1 class="text-lg font-semibold text-slate-100">SSH 传输控制台</h1>
|
||||||
<p class="text-sm text-slate-400">{{ authStore.displayName || authStore.username }}</p>
|
<p class="text-sm text-slate-400">{{ authStore.displayName || authStore.username }}</p>
|
||||||
</div>
|
</div>
|
||||||
<nav class="flex-1 p-4 space-y-1 pt-16 lg:pt-4">
|
<nav class="flex-1 p-4 space-y-1 pt-16 lg:pt-4">
|
||||||
|
<RouterLink
|
||||||
|
to="/transfers"
|
||||||
|
@click="closeSidebar"
|
||||||
|
class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-slate-300 hover:bg-slate-700 hover:text-slate-100 transition-colors duration-200 cursor-pointer min-h-[44px] focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:ring-inset"
|
||||||
|
:class="{ 'bg-slate-700 text-cyan-400': route.path === '/transfers' }"
|
||||||
|
aria-label="传输"
|
||||||
|
>
|
||||||
|
<ArrowLeftRight class="w-5 h-5 flex-shrink-0" aria-hidden="true" />
|
||||||
|
<span>传输</span>
|
||||||
|
</RouterLink>
|
||||||
<RouterLink
|
<RouterLink
|
||||||
to="/connections"
|
to="/connections"
|
||||||
@click="closeSidebar"
|
@click="closeSidebar"
|
||||||
|
|||||||
@@ -19,6 +19,11 @@ const routes: RouteRecordRaw[] = [
|
|||||||
name: 'Home',
|
name: 'Home',
|
||||||
redirect: '/connections',
|
redirect: '/connections',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'transfers',
|
||||||
|
name: 'Transfers',
|
||||||
|
component: () => import('../views/TransfersView.vue'),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'connections',
|
path: 'connections',
|
||||||
name: 'Connections',
|
name: 'Connections',
|
||||||
|
|||||||
389
frontend/src/stores/transfers.ts
Normal file
389
frontend/src/stores/transfers.ts
Normal file
@@ -0,0 +1,389 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref, computed } from 'vue'
|
||||||
|
|
||||||
|
import { createRemoteTransferTask, subscribeRemoteTransferProgress, uploadFileWithProgress } from '../api/sftp'
|
||||||
|
|
||||||
|
export type TransferMode = 'LOCAL_TO_MANY' | 'REMOTE_TO_MANY'
|
||||||
|
export type TransferItemStatus = 'queued' | 'running' | 'success' | 'error' | 'cancelled'
|
||||||
|
|
||||||
|
export interface TransferItem {
|
||||||
|
id: string
|
||||||
|
label: string
|
||||||
|
status: TransferItemStatus
|
||||||
|
message?: string
|
||||||
|
progress?: number
|
||||||
|
startedAt?: number
|
||||||
|
finishedAt?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TransferRun {
|
||||||
|
id: string
|
||||||
|
mode: TransferMode
|
||||||
|
title: string
|
||||||
|
createdAt: number
|
||||||
|
items: TransferItem[]
|
||||||
|
status: TransferItemStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
type RunController = {
|
||||||
|
abortAll: () => void
|
||||||
|
unsubscribers: (() => void)[]
|
||||||
|
}
|
||||||
|
|
||||||
|
function now() {
|
||||||
|
return Date.now()
|
||||||
|
}
|
||||||
|
|
||||||
|
function uid(prefix: string) {
|
||||||
|
return `${prefix}-${now()}-${Math.random().toString(16).slice(2)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function startPseudoProgress(item: TransferItem) {
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
if (item.status !== 'running') {
|
||||||
|
clearInterval(timer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const current = typeof item.progress === 'number' ? item.progress : 0
|
||||||
|
if (current >= 95) return
|
||||||
|
const step = current < 20 ? 3 : current < 60 ? 2 : 1
|
||||||
|
item.progress = Math.min(95, current + step)
|
||||||
|
}, 500)
|
||||||
|
|
||||||
|
return () => clearInterval(timer)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runWithConcurrency<T>(
|
||||||
|
tasks: (() => Promise<T>)[],
|
||||||
|
concurrency: number
|
||||||
|
): Promise<void> {
|
||||||
|
const queue = tasks.slice()
|
||||||
|
const workers: Promise<void>[] = []
|
||||||
|
|
||||||
|
const worker = async () => {
|
||||||
|
while (queue.length) {
|
||||||
|
const task = queue.shift()
|
||||||
|
if (!task) return
|
||||||
|
await task()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const c = Math.max(1, Math.min(concurrency, tasks.length || 1))
|
||||||
|
for (let i = 0; i < c; i++) workers.push(worker())
|
||||||
|
await Promise.allSettled(workers)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForRemoteTransfer(taskId: string, onProgress: (progress: number) => void, unsubscribers: (() => void)[]) {
|
||||||
|
return new Promise<void>((resolve, reject) => {
|
||||||
|
console.log('[waitForRemoteTransfer] Subscribing to task:', taskId)
|
||||||
|
const unsubscribe = subscribeRemoteTransferProgress(taskId, (task) => {
|
||||||
|
const progress = Math.max(0, Math.min(100, task.progress || 0))
|
||||||
|
console.log('[waitForRemoteTransfer] Progress from SSE:', progress, 'status:', task.status)
|
||||||
|
onProgress(progress)
|
||||||
|
|
||||||
|
if (task.status === 'success') {
|
||||||
|
console.log('[waitForRemoteTransfer] Task succeeded:', taskId)
|
||||||
|
resolve()
|
||||||
|
} else if (task.status === 'error') {
|
||||||
|
console.error('[waitForRemoteTransfer] Task errored:', taskId, task.error)
|
||||||
|
reject(new Error(task.error || 'Transfer failed'))
|
||||||
|
} else if (task.status === 'cancelled') {
|
||||||
|
console.log('[waitForRemoteTransfer] Task cancelled:', taskId)
|
||||||
|
reject(new Error('Cancelled'))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
unsubscribers.push(unsubscribe)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildRemoteTransferPath(targetDir: string, filename: string) {
|
||||||
|
let targetPath = targetDir.trim()
|
||||||
|
if (!targetPath) targetPath = '/'
|
||||||
|
if (!targetPath.endsWith('/')) targetPath = targetPath + '/'
|
||||||
|
return targetPath + filename
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useTransfersStore = defineStore('transfers', () => {
|
||||||
|
const runs = ref<TransferRun[]>([] as TransferRun[])
|
||||||
|
const controllers = new Map<string, RunController>()
|
||||||
|
|
||||||
|
const recentRuns = computed(() => runs.value.slice(0, 20))
|
||||||
|
|
||||||
|
function clearRuns() {
|
||||||
|
for (const c of controllers.values()) {
|
||||||
|
try {
|
||||||
|
c.abortAll()
|
||||||
|
for (const unsub of c.unsubscribers) {
|
||||||
|
try {
|
||||||
|
unsub()
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
controllers.clear()
|
||||||
|
runs.value = []
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelRun(runId: string) {
|
||||||
|
const runIndex = runs.value.findIndex((r) => r.id === runId)
|
||||||
|
if (runIndex === -1) return
|
||||||
|
const ctrl = controllers.get(runId)
|
||||||
|
if (ctrl) {
|
||||||
|
ctrl.abortAll()
|
||||||
|
for (const unsub of ctrl.unsubscribers) {
|
||||||
|
try {
|
||||||
|
unsub()
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const run = runs.value[runIndex]!
|
||||||
|
run.items.forEach((item) => {
|
||||||
|
if (item.status === 'queued' || item.status === 'running') {
|
||||||
|
item.status = 'cancelled'
|
||||||
|
item.progress = 100
|
||||||
|
item.finishedAt = now()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startLocalToMany(params: {
|
||||||
|
files: File[]
|
||||||
|
targetConnectionIds: number[]
|
||||||
|
targetDir: string
|
||||||
|
concurrency?: number
|
||||||
|
}) {
|
||||||
|
const { files, targetConnectionIds, targetDir } = params
|
||||||
|
const concurrency = params.concurrency ?? 3
|
||||||
|
|
||||||
|
const runId = uid('run')
|
||||||
|
const runItems: TransferItem[] = []
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
for (const connectionId of targetConnectionIds) {
|
||||||
|
runItems.push({
|
||||||
|
id: uid('item'),
|
||||||
|
label: `${file.name} -> #${connectionId}:${targetDir || ''}`,
|
||||||
|
status: 'queued' as const,
|
||||||
|
progress: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const run: TransferRun = {
|
||||||
|
id: runId,
|
||||||
|
mode: 'LOCAL_TO_MANY' as const,
|
||||||
|
title: `Local -> ${targetConnectionIds.length} targets`,
|
||||||
|
createdAt: now(),
|
||||||
|
items: runItems,
|
||||||
|
status: 'queued' as const,
|
||||||
|
}
|
||||||
|
|
||||||
|
runs.value = [run, ...runs.value]
|
||||||
|
|
||||||
|
const activeXhrs: XMLHttpRequest[] = []
|
||||||
|
const unsubscribers: (() => void)[] = []
|
||||||
|
controllers.set(runId, {
|
||||||
|
abortAll: () => {
|
||||||
|
for (const xhr of activeXhrs) {
|
||||||
|
try {
|
||||||
|
xhr.abort()
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
unsubscribers,
|
||||||
|
})
|
||||||
|
|
||||||
|
const tasks: (() => Promise<void>)[] = []
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
for (const connectionId of targetConnectionIds) {
|
||||||
|
const itemIndex = runItems.findIndex((i) => i.label.includes(file.name) && i.label.includes(`#${connectionId}`))
|
||||||
|
if (itemIndex === -1) continue
|
||||||
|
const item = runItems[itemIndex]!
|
||||||
|
tasks.push(async () => {
|
||||||
|
if (item.status === 'cancelled') return
|
||||||
|
item.status = 'running'
|
||||||
|
item.progress = 0
|
||||||
|
item.startedAt = now()
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
const stopPseudoProgress = startPseudoProgress(item)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const xhr = uploadFileWithProgress(connectionId, targetDir || '', file)
|
||||||
|
activeXhrs.push(xhr)
|
||||||
|
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
let lastTick = 0
|
||||||
|
xhr.onProgress = (percent) => {
|
||||||
|
console.log('[Transfers] onProgress callback fired:', percent, 'item:', item.label)
|
||||||
|
const t = now()
|
||||||
|
if (t - lastTick < 100 && percent !== 100) return
|
||||||
|
lastTick = t
|
||||||
|
const newProgress = Math.max(item.progress || 0, Math.max(0, Math.min(100, percent)))
|
||||||
|
console.log('[Transfers] Updating item.progress from', item.progress, 'to', newProgress)
|
||||||
|
item.progress = newProgress
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
}
|
||||||
|
console.log('[Transfers] Set onProgress callback for:', item.label)
|
||||||
|
xhr.onload = () => {
|
||||||
|
if (xhr.status >= 200 && xhr.status < 300) resolve()
|
||||||
|
else reject(new Error(xhr.responseText || `HTTP ${xhr.status}`))
|
||||||
|
}
|
||||||
|
xhr.onerror = () => reject(new Error('Network error'))
|
||||||
|
xhr.onabort = () => reject(new Error('Cancelled'))
|
||||||
|
})
|
||||||
|
|
||||||
|
item.status = 'success'
|
||||||
|
item.progress = 100
|
||||||
|
item.finishedAt = now()
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
} catch (e: unknown) {
|
||||||
|
const msg = (e as Error)?.message || 'Upload failed'
|
||||||
|
if (msg === 'Cancelled') {
|
||||||
|
item.status = 'cancelled'
|
||||||
|
item.progress = 100
|
||||||
|
} else {
|
||||||
|
item.status = 'error'
|
||||||
|
item.progress = 100
|
||||||
|
item.message = msg
|
||||||
|
}
|
||||||
|
item.finishedAt = now()
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
} finally {
|
||||||
|
stopPseudoProgress()
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await runWithConcurrency(tasks, concurrency)
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startRemoteToMany(params: {
|
||||||
|
sourceConnectionId: number
|
||||||
|
sourcePath: string
|
||||||
|
targetConnectionIds: number[]
|
||||||
|
targetDirOrPath: string
|
||||||
|
concurrency?: number
|
||||||
|
}) {
|
||||||
|
const { sourceConnectionId, sourcePath, targetConnectionIds, targetDirOrPath } = params
|
||||||
|
const concurrency = params.concurrency ?? 3
|
||||||
|
|
||||||
|
if (sourceConnectionId == null) return
|
||||||
|
|
||||||
|
const runId = uid('run')
|
||||||
|
const filename = sourcePath.split('/').filter(Boolean).pop() || sourcePath
|
||||||
|
const runItems: TransferItem[] = targetConnectionIds.map((targetId) => ({
|
||||||
|
id: uid('item'),
|
||||||
|
label: `#${sourceConnectionId}:${sourcePath} -> #${targetId}:${targetDirOrPath}`,
|
||||||
|
status: 'queued' as const,
|
||||||
|
progress: 0,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const run: TransferRun = {
|
||||||
|
id: runId,
|
||||||
|
mode: 'REMOTE_TO_MANY' as const,
|
||||||
|
title: `Remote ${filename} -> ${targetConnectionIds.length} targets`,
|
||||||
|
createdAt: now(),
|
||||||
|
items: runItems,
|
||||||
|
status: 'queued' as const,
|
||||||
|
}
|
||||||
|
|
||||||
|
runs.value = [run, ...runs.value]
|
||||||
|
|
||||||
|
let cancelled = false
|
||||||
|
const unsubscribers: (() => void)[] = []
|
||||||
|
controllers.set(runId, {
|
||||||
|
abortAll: () => {
|
||||||
|
cancelled = true
|
||||||
|
},
|
||||||
|
unsubscribers,
|
||||||
|
})
|
||||||
|
|
||||||
|
const tasks = runItems.map((item, index) => {
|
||||||
|
return async () => {
|
||||||
|
const targetId = targetConnectionIds[index]
|
||||||
|
if (targetId == null) {
|
||||||
|
item.status = 'error'
|
||||||
|
item.progress = 100
|
||||||
|
item.message = 'Missing target connection'
|
||||||
|
item.finishedAt = now()
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (cancelled) {
|
||||||
|
item.status = 'cancelled'
|
||||||
|
item.progress = 100
|
||||||
|
item.finishedAt = now()
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
return
|
||||||
|
}
|
||||||
|
item.status = 'running'
|
||||||
|
item.progress = 0
|
||||||
|
item.startedAt = now()
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
console.log('[Remote->Many] Starting transfer:', item.label, 'targetId:', targetId)
|
||||||
|
try {
|
||||||
|
const targetPath = buildRemoteTransferPath(targetDirOrPath, filename)
|
||||||
|
console.log('[Remote->Many] Target path:', targetPath)
|
||||||
|
|
||||||
|
const task = await createRemoteTransferTask(sourceConnectionId, sourcePath, targetId, targetPath)
|
||||||
|
const taskId = task.data.taskId
|
||||||
|
console.log('[Remote->Many] Task created:', taskId)
|
||||||
|
await waitForRemoteTransfer(taskId, (progress) => {
|
||||||
|
console.log('[Remote->Many] Progress update:', progress, 'item:', item.label)
|
||||||
|
item.progress = Math.max(item.progress || 0, progress)
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
}, unsubscribers)
|
||||||
|
|
||||||
|
item.status = 'success'
|
||||||
|
item.progress = 100
|
||||||
|
item.finishedAt = now()
|
||||||
|
console.log('[Remote->Many] Transfer completed:', item.label)
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
} catch (e: unknown) {
|
||||||
|
const err = e as { response?: { data?: { error?: string } } }
|
||||||
|
const msg = err?.response?.data?.error || (e as Error)?.message || 'Transfer failed'
|
||||||
|
console.error('[Remote->Many] Transfer failed:', item.label, 'error:', msg)
|
||||||
|
if (msg === 'Cancelled') {
|
||||||
|
item.status = 'cancelled'
|
||||||
|
item.progress = 100
|
||||||
|
} else {
|
||||||
|
item.status = 'error'
|
||||||
|
item.progress = 100
|
||||||
|
item.message = msg
|
||||||
|
}
|
||||||
|
item.finishedAt = now()
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
} finally {
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
await runWithConcurrency(tasks, concurrency)
|
||||||
|
runs.value = [...runs.value]
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
runs,
|
||||||
|
recentRuns,
|
||||||
|
controllers,
|
||||||
|
clearRuns,
|
||||||
|
cancelRun,
|
||||||
|
startLocalToMany,
|
||||||
|
startRemoteToMany,
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -3,8 +3,28 @@
|
|||||||
@tailwind utilities;
|
@tailwind utilities;
|
||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
|
:root {
|
||||||
|
--app-bg-0: #0b1220;
|
||||||
|
--app-bg-1: #0a1626;
|
||||||
|
--app-card: rgba(17, 24, 39, 0.72);
|
||||||
|
--app-border: rgba(148, 163, 184, 0.18);
|
||||||
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
@apply bg-slate-900 text-slate-100 antialiased;
|
font-family: "IBM Plex Sans", ui-sans-serif, system-ui, -apple-system, Segoe UI, sans-serif;
|
||||||
|
@apply text-slate-100 antialiased;
|
||||||
|
background:
|
||||||
|
radial-gradient(1200px 600px at 10% -10%, rgba(34, 211, 238, 0.16), transparent 60%),
|
||||||
|
radial-gradient(900px 500px at 90% 0%, rgba(59, 130, 246, 0.10), transparent 55%),
|
||||||
|
linear-gradient(180deg, var(--app-bg-0), var(--app-bg-1));
|
||||||
|
}
|
||||||
|
|
||||||
|
code,
|
||||||
|
kbd,
|
||||||
|
samp,
|
||||||
|
pre {
|
||||||
|
font-family: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",
|
||||||
|
"Courier New", monospace;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -60,11 +60,11 @@ watch([searchQuery, showHiddenFiles, files], () => {
|
|||||||
|
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
clearTimeout(searchDebounceTimer)
|
clearTimeout(searchDebounceTimer)
|
||||||
|
stopTransferProgress()
|
||||||
})
|
})
|
||||||
|
|
||||||
const showUploadProgress = ref(false)
|
const showUploadProgress = ref(false)
|
||||||
const uploadProgressList = ref<{ id: string; name: string; size: number; uploaded: number; total: number; status: 'pending' | 'uploading' | 'success' | 'error'; message?: string }[]>([])
|
const uploadProgressList = ref<{ id: string; name: string; size: number; uploaded: number; total: number; status: 'pending' | 'uploading' | 'success' | 'error'; message?: string }[]>([])
|
||||||
const lastUpdate = ref(0)
|
|
||||||
|
|
||||||
const totalProgress = computed(() => {
|
const totalProgress = computed(() => {
|
||||||
if (uploadProgressList.value.length === 0) return 0
|
if (uploadProgressList.value.length === 0) return 0
|
||||||
@@ -97,6 +97,72 @@ const transferTargetConnectionId = ref<number | null>(null)
|
|||||||
const transferTargetPath = ref('')
|
const transferTargetPath = ref('')
|
||||||
const transferring = ref(false)
|
const transferring = ref(false)
|
||||||
const transferError = ref('')
|
const transferError = ref('')
|
||||||
|
const transferProgress = ref(0)
|
||||||
|
const transferTransferredBytes = ref(0)
|
||||||
|
const transferTotalBytes = ref(0)
|
||||||
|
const transferTaskId = ref('')
|
||||||
|
let transferPollAbort = false
|
||||||
|
|
||||||
|
function resetTransferProgress() {
|
||||||
|
transferProgress.value = 0
|
||||||
|
transferTransferredBytes.value = 0
|
||||||
|
transferTotalBytes.value = 0
|
||||||
|
transferTaskId.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopTransferProgress() {
|
||||||
|
transferPollAbort = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTransferBytes(bytes: number) {
|
||||||
|
return formatSize(Math.max(0, bytes || 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForTransferTask(taskId: string) {
|
||||||
|
transferPollAbort = false
|
||||||
|
transferTaskId.value = taskId
|
||||||
|
while (!transferPollAbort) {
|
||||||
|
const res = await sftpApi.getRemoteTransferTask(taskId)
|
||||||
|
const task = res.data
|
||||||
|
transferProgress.value = Math.max(0, Math.min(100, task.progress || 0))
|
||||||
|
transferTransferredBytes.value = Math.max(0, task.transferredBytes || 0)
|
||||||
|
transferTotalBytes.value = Math.max(0, task.totalBytes || 0)
|
||||||
|
|
||||||
|
if (task.status === 'success') return task
|
||||||
|
if (task.status === 'error') throw new Error(task.error || '传输失败')
|
||||||
|
if (task.status === 'cancelled') throw new Error('传输已取消')
|
||||||
|
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('传输已取消')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cancelTransfer() {
|
||||||
|
const taskId = transferTaskId.value
|
||||||
|
stopTransferProgress()
|
||||||
|
if (!taskId) {
|
||||||
|
transferring.value = false
|
||||||
|
transferError.value = '传输已取消'
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await sftpApi.cancelRemoteTransferTask(taskId)
|
||||||
|
const task = res.data
|
||||||
|
transferProgress.value = Math.max(0, Math.min(100, task.progress || transferProgress.value))
|
||||||
|
transferTransferredBytes.value = Math.max(0, task.transferredBytes || transferTransferredBytes.value)
|
||||||
|
transferTotalBytes.value = Math.max(0, task.totalBytes || transferTotalBytes.value)
|
||||||
|
if (task.cancelRequested) {
|
||||||
|
transferError.value = '已请求取消传输'
|
||||||
|
} else {
|
||||||
|
transferError.value = task.message || '当前传输正在收尾,稍后会结束'
|
||||||
|
}
|
||||||
|
} catch (err: unknown) {
|
||||||
|
const res = err as { response?: { data?: { error?: string } } }
|
||||||
|
transferError.value = res?.response?.data?.error ?? '取消传输失败'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
conn.value = store.getConnection(connectionId.value)
|
conn.value = store.getConnection(connectionId.value)
|
||||||
@@ -208,7 +274,7 @@ async function handleFileSelect(e: Event) {
|
|||||||
error.value = ''
|
error.value = ''
|
||||||
const path = currentPath.value === '.' ? '' : currentPath.value
|
const path = currentPath.value === '.' ? '' : currentPath.value
|
||||||
|
|
||||||
const uploadTasks: { id: string; file: File }[] = []
|
const uploadTasks: { id: string; file: File; taskId?: string }[] = []
|
||||||
for (let i = 0; i < selected.length; i++) {
|
for (let i = 0; i < selected.length; i++) {
|
||||||
const file = selected[i]
|
const file = selected[i]
|
||||||
if (!file) continue
|
if (!file) continue
|
||||||
@@ -227,51 +293,56 @@ async function handleFileSelect(e: Event) {
|
|||||||
showUploadProgress.value = true
|
showUploadProgress.value = true
|
||||||
|
|
||||||
const MAX_PARALLEL = 5
|
const MAX_PARALLEL = 5
|
||||||
const results: Promise<void>[] = []
|
|
||||||
|
|
||||||
for (let i = 0; i < uploadTasks.length; i += MAX_PARALLEL) {
|
for (let i = 0; i < uploadTasks.length; i += MAX_PARALLEL) {
|
||||||
const batch = uploadTasks.slice(i, i + MAX_PARALLEL)
|
const batch = uploadTasks.slice(i, i + MAX_PARALLEL)
|
||||||
const batchPromises = batch.map(task => {
|
const batchPromises = batch.map(async task => {
|
||||||
if (!task) return Promise.resolve()
|
if (!task) return
|
||||||
const { id, file } = task
|
const { id, file } = task
|
||||||
const item = uploadProgressList.value.find(item => item.id === id)
|
const item = uploadProgressList.value.find(item => item.id === id)
|
||||||
if (!item) return Promise.resolve()
|
if (!item) return
|
||||||
|
|
||||||
item.status = 'uploading'
|
item.status = 'uploading'
|
||||||
|
|
||||||
return new Promise<void>((resolve, reject) => {
|
try {
|
||||||
const onProgress = (percent: number) => {
|
// Start upload and get taskId
|
||||||
const now = Date.now()
|
const uploadRes = await sftpApi.uploadFile(connectionId.value, path, file)
|
||||||
if (now - (lastUpdate.value || 0) > 100) {
|
const taskId = uploadRes.data.taskId
|
||||||
item.uploaded = Math.round((file.size * percent) / 100)
|
|
||||||
item.total = file.size
|
// Poll for progress
|
||||||
lastUpdate.value = now
|
while (true) {
|
||||||
}
|
const statusRes = await sftpApi.getUploadTask(taskId)
|
||||||
}
|
const taskStatus = statusRes.data
|
||||||
const xhr = sftpApi.uploadFileWithProgress(connectionId.value, path, file)
|
|
||||||
xhr.onProgress = onProgress
|
item.uploaded = taskStatus.transferredBytes
|
||||||
xhr.onload = () => {
|
item.total = taskStatus.totalBytes
|
||||||
|
|
||||||
|
if (taskStatus.status === 'success') {
|
||||||
item.status = 'success'
|
item.status = 'success'
|
||||||
resolve()
|
break
|
||||||
}
|
}
|
||||||
xhr.onerror = () => {
|
if (taskStatus.status === 'error') {
|
||||||
item.status = 'error'
|
item.status = 'error'
|
||||||
item.message = 'Network error'
|
item.message = taskStatus.error || 'Upload failed'
|
||||||
reject(new Error('Network error'))
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 200))
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
item.status = 'error'
|
||||||
|
item.message = err?.response?.data?.error || 'Upload failed'
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
|
||||||
results.push(...batchPromises)
|
|
||||||
await Promise.allSettled(batchPromises)
|
await Promise.allSettled(batchPromises)
|
||||||
}
|
}
|
||||||
|
|
||||||
await Promise.allSettled(results)
|
|
||||||
await loadPath()
|
await loadPath()
|
||||||
|
const successCount = uploadProgressList.value.filter(item => item.status === 'success').length
|
||||||
showUploadProgress.value = false
|
showUploadProgress.value = false
|
||||||
uploadProgressList.value = []
|
uploadProgressList.value = []
|
||||||
uploading.value = false
|
uploading.value = false
|
||||||
fileInputRef.value!.value = ''
|
fileInputRef.value!.value = ''
|
||||||
const successCount = uploadProgressList.value.filter(item => item.status === 'success').length
|
|
||||||
toast.success(`成功上传 ${successCount} 个文件`)
|
toast.success(`成功上传 ${successCount} 个文件`)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -311,11 +382,14 @@ async function openTransferModal(file: SftpFileInfo) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function closeTransferModal() {
|
function closeTransferModal() {
|
||||||
|
if (transferring.value) return
|
||||||
|
stopTransferProgress()
|
||||||
showTransferModal.value = false
|
showTransferModal.value = false
|
||||||
transferFile.value = null
|
transferFile.value = null
|
||||||
transferTargetConnectionId.value = null
|
transferTargetConnectionId.value = null
|
||||||
transferTargetPath.value = ''
|
transferTargetPath.value = ''
|
||||||
transferError.value = ''
|
transferError.value = ''
|
||||||
|
resetTransferProgress()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submitTransfer() {
|
async function submitTransfer() {
|
||||||
@@ -328,14 +402,18 @@ async function submitTransfer() {
|
|||||||
if (targetPath.endsWith('/') || !targetPath) targetPath = targetPath + file.name
|
if (targetPath.endsWith('/') || !targetPath) targetPath = targetPath + file.name
|
||||||
transferring.value = true
|
transferring.value = true
|
||||||
transferError.value = ''
|
transferError.value = ''
|
||||||
|
resetTransferProgress()
|
||||||
try {
|
try {
|
||||||
await sftpApi.transferRemote(connectionId.value, sourcePath, targetId, targetPath)
|
const created = await sftpApi.createRemoteTransferTask(connectionId.value, sourcePath, targetId, targetPath)
|
||||||
loadPath()
|
await waitForTransferTask(created.data.taskId)
|
||||||
|
transferProgress.value = 100
|
||||||
|
await loadPath()
|
||||||
closeTransferModal()
|
closeTransferModal()
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
const res = err as { response?: { data?: { error?: string } } }
|
const res = err as { response?: { data?: { error?: string } } }
|
||||||
transferError.value = res?.response?.data?.error ?? '传输失败'
|
transferError.value = res?.response?.data?.error ?? (err as Error)?.message ?? '传输失败'
|
||||||
} finally {
|
} finally {
|
||||||
|
stopTransferProgress()
|
||||||
transferring.value = false
|
transferring.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -570,14 +648,29 @@ async function submitTransfer() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p v-if="transferError" class="mt-3 text-sm text-red-400">{{ transferError }}</p>
|
<p v-if="transferError" class="mt-3 text-sm text-red-400">{{ transferError }}</p>
|
||||||
|
<div v-if="transferring" class="mt-3 space-y-2">
|
||||||
|
<div class="flex items-center justify-between text-xs text-slate-400">
|
||||||
|
<span>传输进度</span>
|
||||||
|
<span>{{ transferProgress }}%</span>
|
||||||
|
</div>
|
||||||
|
<div class="h-2 overflow-hidden rounded-full bg-slate-700">
|
||||||
|
<div
|
||||||
|
class="h-full bg-cyan-500 transition-all duration-300"
|
||||||
|
:style="{ width: transferProgress + '%' }"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between text-[11px] text-slate-500">
|
||||||
|
<span>{{ formatTransferBytes(transferTransferredBytes) }}</span>
|
||||||
|
<span>{{ transferTotalBytes > 0 ? formatTransferBytes(transferTotalBytes) : '--' }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="mt-5 flex justify-end gap-2">
|
<div class="mt-5 flex justify-end gap-2">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@click="closeTransferModal"
|
@click="transferring ? cancelTransfer() : closeTransferModal()"
|
||||||
:disabled="transferring"
|
class="rounded-lg border border-slate-600 px-4 py-2 text-slate-300 hover:bg-slate-700 cursor-pointer"
|
||||||
class="rounded-lg border border-slate-600 px-4 py-2 text-slate-300 hover:bg-slate-700 disabled:opacity-50 cursor-pointer"
|
|
||||||
>
|
>
|
||||||
取消
|
{{ transferring ? '取消传输' : '取消' }}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
516
frontend/src/views/TransfersView.vue
Normal file
516
frontend/src/views/TransfersView.vue
Normal file
@@ -0,0 +1,516 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
|
||||||
|
import { useConnectionsStore } from '../stores/connections'
|
||||||
|
import { useTransfersStore } from '../stores/transfers'
|
||||||
|
import SftpFilePickerModal from '../components/SftpFilePickerModal.vue'
|
||||||
|
|
||||||
|
import {
|
||||||
|
ArrowUpRight,
|
||||||
|
ArrowLeftRight,
|
||||||
|
CloudUpload,
|
||||||
|
FolderOpen,
|
||||||
|
XCircle,
|
||||||
|
CheckCircle2,
|
||||||
|
AlertTriangle,
|
||||||
|
Loader2,
|
||||||
|
Trash2,
|
||||||
|
} from 'lucide-vue-next'
|
||||||
|
|
||||||
|
type Tab = 'local' | 'remote'
|
||||||
|
|
||||||
|
const connectionsStore = useConnectionsStore()
|
||||||
|
const transfersStore = useTransfersStore()
|
||||||
|
|
||||||
|
const tab = ref<Tab>('local')
|
||||||
|
|
||||||
|
// Local -> many
|
||||||
|
const localFiles = ref<File[]>([])
|
||||||
|
const localTargetDir = ref('/')
|
||||||
|
const localSelectedTargets = ref<number[]>([])
|
||||||
|
const localConcurrency = ref(3)
|
||||||
|
|
||||||
|
// Remote -> many
|
||||||
|
const remoteSourceConnectionId = ref<number | null>(null)
|
||||||
|
const remoteSourcePath = ref('')
|
||||||
|
const remoteTargetDirOrPath = ref('/')
|
||||||
|
const remoteSelectedTargets = ref<number[]>([])
|
||||||
|
const remoteConcurrency = ref(3)
|
||||||
|
|
||||||
|
// Picker
|
||||||
|
const pickerOpen = ref(false)
|
||||||
|
|
||||||
|
const connections = computed(() => connectionsStore.connections)
|
||||||
|
const connectionOptions = computed(() => connections.value.slice().sort((a, b) => a.name.localeCompare(b.name)))
|
||||||
|
|
||||||
|
// Remote -> Many 模式下的目标连接列表(排除源连接)
|
||||||
|
const remoteTargetConnectionOptions = computed(() =>
|
||||||
|
connectionOptions.value.filter((c) => c.id !== remoteSourceConnectionId.value)
|
||||||
|
)
|
||||||
|
|
||||||
|
const canStartLocal = computed(() => localFiles.value.length > 0 && localSelectedTargets.value.length > 0)
|
||||||
|
const canStartRemote = computed(
|
||||||
|
() => remoteSourceConnectionId.value != null && remoteSourcePath.value.trim() && remoteSelectedTargets.value.length > 0
|
||||||
|
)
|
||||||
|
|
||||||
|
function onLocalFileChange(e: Event) {
|
||||||
|
const input = e.target as HTMLInputElement
|
||||||
|
const list = input.files
|
||||||
|
if (!list) return
|
||||||
|
localFiles.value = Array.from(list)
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectAllLocalTargets() {
|
||||||
|
localSelectedTargets.value = connectionOptions.value.map((c) => c.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearLocalTargets() {
|
||||||
|
localSelectedTargets.value = []
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectAllRemoteTargets() {
|
||||||
|
remoteSelectedTargets.value = remoteTargetConnectionOptions.value.map((c) => c.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearRemoteTargets() {
|
||||||
|
remoteSelectedTargets.value = []
|
||||||
|
}
|
||||||
|
|
||||||
|
function humanRunStatus(status: string) {
|
||||||
|
if (status === 'queued') return 'Queued'
|
||||||
|
if (status === 'running') return 'Running'
|
||||||
|
if (status === 'success') return 'Success'
|
||||||
|
if (status === 'error') return 'Error'
|
||||||
|
if (status === 'cancelled') return 'Cancelled'
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
|
||||||
|
function runBadgeClass(status: string) {
|
||||||
|
if (status === 'success') return 'bg-emerald-500/10 text-emerald-200 border-emerald-500/20'
|
||||||
|
if (status === 'error') return 'bg-red-500/10 text-red-200 border-red-500/20'
|
||||||
|
if (status === 'running') return 'bg-cyan-500/10 text-cyan-200 border-cyan-500/20'
|
||||||
|
if (status === 'cancelled') return 'bg-slate-500/10 text-slate-200 border-slate-500/20'
|
||||||
|
return 'bg-amber-500/10 text-amber-200 border-amber-500/20'
|
||||||
|
}
|
||||||
|
|
||||||
|
function runProgressPercent(run: { items: { status: string; progress?: number }[]; lastUpdate?: number }) {
|
||||||
|
// Access lastUpdate to ensure reactivity
|
||||||
|
void run.lastUpdate
|
||||||
|
const items = run.items
|
||||||
|
if (!items.length) return 0
|
||||||
|
let sum = 0
|
||||||
|
for (const it of items) {
|
||||||
|
if (it.status === 'success' || it.status === 'error' || it.status === 'cancelled') {
|
||||||
|
sum += 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (it.status === 'running') {
|
||||||
|
const p = typeof it.progress === 'number' ? it.progress : 0
|
||||||
|
sum += Math.max(0, Math.min(1, p / 100))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// queued
|
||||||
|
sum += 0
|
||||||
|
}
|
||||||
|
return Math.round((sum / items.length) * 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startLocal() {
|
||||||
|
if (!canStartLocal.value) return
|
||||||
|
await transfersStore.startLocalToMany({
|
||||||
|
files: localFiles.value,
|
||||||
|
targetConnectionIds: localSelectedTargets.value,
|
||||||
|
targetDir: localTargetDir.value,
|
||||||
|
concurrency: localConcurrency.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startRemote() {
|
||||||
|
if (!canStartRemote.value || remoteSourceConnectionId.value == null) return
|
||||||
|
await transfersStore.startRemoteToMany({
|
||||||
|
sourceConnectionId: remoteSourceConnectionId.value,
|
||||||
|
sourcePath: remoteSourcePath.value.trim(),
|
||||||
|
targetConnectionIds: remoteSelectedTargets.value,
|
||||||
|
targetDirOrPath: remoteTargetDirOrPath.value,
|
||||||
|
concurrency: remoteConcurrency.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function openPicker() {
|
||||||
|
if (remoteSourceConnectionId.value == null) return
|
||||||
|
pickerOpen.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
if (connectionsStore.connections.length === 0) {
|
||||||
|
await connectionsStore.fetchConnections().catch(() => {})
|
||||||
|
}
|
||||||
|
if (remoteSourceConnectionId.value == null) {
|
||||||
|
remoteSourceConnectionId.value = connectionOptions.value[0]?.id ?? null
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="p-6 lg:p-8">
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<div class="flex items-center justify-between gap-4">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<h1 class="text-2xl font-semibold tracking-tight text-slate-50">Transfers</h1>
|
||||||
|
<p class="text-sm text-slate-400">本机 -> 多台 / 其他机器 -> 多台</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
@click="transfersStore.clearRuns"
|
||||||
|
class="min-h-[44px] inline-flex items-center gap-2 px-3 rounded-lg border border-slate-700 bg-slate-900/40 text-slate-200 hover:bg-slate-800/60 transition-colors cursor-pointer"
|
||||||
|
aria-label="清空队列"
|
||||||
|
>
|
||||||
|
<Trash2 class="w-4 h-4" aria-hidden="true" />
|
||||||
|
清空队列
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4 grid gap-3 sm:grid-cols-2">
|
||||||
|
<button
|
||||||
|
@click="tab = 'local'"
|
||||||
|
class="rounded-2xl border p-4 text-left transition-colors cursor-pointer min-h-[88px]"
|
||||||
|
:class="tab === 'local' ? 'border-cyan-500/40 bg-slate-900/55' : 'border-slate-800 bg-slate-900/35 hover:bg-slate-900/45'"
|
||||||
|
aria-label="切换到本机上传"
|
||||||
|
>
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
<div class="w-10 h-10 rounded-xl bg-cyan-500/10 border border-cyan-500/20 grid place-items-center">
|
||||||
|
<CloudUpload class="w-5 h-5 text-cyan-200" aria-hidden="true" />
|
||||||
|
</div>
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="text-sm font-medium text-slate-100">Local -> Many</p>
|
||||||
|
<p class="text-xs text-slate-400">选择本机文件,分发到多个目标连接</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
@click="tab = 'remote'"
|
||||||
|
class="rounded-2xl border p-4 text-left transition-colors cursor-pointer min-h-[88px]"
|
||||||
|
:class="tab === 'remote' ? 'border-cyan-500/40 bg-slate-900/55' : 'border-slate-800 bg-slate-900/35 hover:bg-slate-900/45'"
|
||||||
|
aria-label="切换到远程转发"
|
||||||
|
>
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
<div class="w-10 h-10 rounded-xl bg-cyan-500/10 border border-cyan-500/20 grid place-items-center">
|
||||||
|
<ArrowLeftRight class="w-5 h-5 text-cyan-200" aria-hidden="true" />
|
||||||
|
</div>
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="text-sm font-medium text-slate-100">Remote -> Many</p>
|
||||||
|
<p class="text-xs text-slate-400">从一台机器取文件,推送到多个目标连接</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-6 grid gap-6 lg:grid-cols-[1fr_460px]">
|
||||||
|
<section class="rounded-2xl border border-slate-800 bg-slate-900/40 backdrop-blur p-5">
|
||||||
|
<div v-if="connections.length === 0" class="text-slate-300">
|
||||||
|
<p class="text-sm">暂无连接。请先在 Connections 里添加连接。</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else>
|
||||||
|
<div v-if="tab === 'local'" class="space-y-4">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<h2 class="text-lg font-semibold text-slate-100">Local -> Many</h2>
|
||||||
|
<span class="text-xs text-slate-400">并发: {{ localConcurrency }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-3">
|
||||||
|
<label class="text-sm text-slate-300">选择本机文件</label>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
multiple
|
||||||
|
class="block w-full rounded-xl border border-slate-700 bg-slate-950/30 px-3 py-2 text-sm text-slate-200 file:mr-3 file:rounded-lg file:border-0 file:bg-slate-800 file:px-3 file:py-2 file:text-slate-200 hover:file:bg-slate-700"
|
||||||
|
@change="onLocalFileChange"
|
||||||
|
aria-label="选择本机文件"
|
||||||
|
/>
|
||||||
|
<p class="text-xs text-slate-500">
|
||||||
|
已选择 {{ localFiles.length }} 个文件
|
||||||
|
<span v-if="localFiles.length">(只支持文件,目录请先打包)</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-3">
|
||||||
|
<label for="local-target-dir" class="text-sm text-slate-300">目标目录</label>
|
||||||
|
<input
|
||||||
|
id="local-target-dir"
|
||||||
|
v-model="localTargetDir"
|
||||||
|
type="text"
|
||||||
|
placeholder="/"
|
||||||
|
class="w-full rounded-xl border border-slate-700 bg-slate-950/30 px-3 py-2 text-sm text-slate-100 placeholder-slate-600 focus:outline-none focus:ring-2 focus:ring-cyan-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-3">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<label class="text-sm text-slate-300">目标连接</label>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
@click="selectAllLocalTargets"
|
||||||
|
class="min-h-[44px] px-3 rounded-lg border border-slate-700 bg-slate-900/30 text-slate-200 hover:bg-slate-800/50 transition-colors cursor-pointer text-sm"
|
||||||
|
>
|
||||||
|
全选
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
@click="clearLocalTargets"
|
||||||
|
class="min-h-[44px] px-3 rounded-lg border border-slate-700 bg-slate-900/30 text-slate-200 hover:bg-slate-800/50 transition-colors cursor-pointer text-sm"
|
||||||
|
>
|
||||||
|
清空
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-2 sm:grid-cols-2">
|
||||||
|
<label
|
||||||
|
v-for="c in connectionOptions"
|
||||||
|
:key="c.id"
|
||||||
|
class="flex items-center gap-3 rounded-xl border border-slate-800 bg-slate-950/20 px-3 py-2 min-h-[44px] cursor-pointer hover:bg-slate-950/30"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
v-model.number="localSelectedTargets"
|
||||||
|
:value="c.id"
|
||||||
|
type="checkbox"
|
||||||
|
class="h-4 w-4 rounded border-slate-600 bg-slate-900 text-cyan-500 focus:ring-cyan-500"
|
||||||
|
/>
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="text-sm text-slate-100 truncate">{{ c.name }}</p>
|
||||||
|
<p class="text-xs text-slate-500 truncate">{{ c.username }}@{{ c.host }}:{{ c.port }}</p>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-2">
|
||||||
|
<label for="local-concurrency" class="text-sm text-slate-300">并发</label>
|
||||||
|
<input
|
||||||
|
id="local-concurrency"
|
||||||
|
v-model.number="localConcurrency"
|
||||||
|
type="range"
|
||||||
|
min="1"
|
||||||
|
max="6"
|
||||||
|
class="w-full"
|
||||||
|
/>
|
||||||
|
<p class="text-xs text-slate-500">建议 2-4。并发越高越吃带宽与 CPU。</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
@click="startLocal"
|
||||||
|
:disabled="!canStartLocal"
|
||||||
|
class="min-h-[44px] inline-flex items-center justify-center gap-2 rounded-xl bg-cyan-600 px-4 py-2 text-sm font-medium text-white hover:bg-cyan-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
|
aria-label="开始上传"
|
||||||
|
>
|
||||||
|
<ArrowUpRight class="w-4 h-4" aria-hidden="true" />
|
||||||
|
开始分发
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else class="space-y-4">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<h2 class="text-lg font-semibold text-slate-100">Remote -> Many</h2>
|
||||||
|
<span class="text-xs text-slate-400">并发: {{ remoteConcurrency }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-3">
|
||||||
|
<label for="remote-source-conn" class="text-sm text-slate-300">源连接</label>
|
||||||
|
<select
|
||||||
|
id="remote-source-conn"
|
||||||
|
v-model.number="remoteSourceConnectionId"
|
||||||
|
class="w-full min-h-[44px] rounded-xl border border-slate-700 bg-slate-950/30 px-3 py-2 text-sm text-slate-100 focus:outline-none focus:ring-2 focus:ring-cyan-500"
|
||||||
|
>
|
||||||
|
<option v-for="c in connectionOptions" :key="c.id" :value="c.id">{{ c.name }} ({{ c.username }}@{{ c.host }})</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-3">
|
||||||
|
<label for="remote-source-path" class="text-sm text-slate-300">源文件路径</label>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input
|
||||||
|
id="remote-source-path"
|
||||||
|
v-model="remoteSourcePath"
|
||||||
|
type="text"
|
||||||
|
placeholder="/path/to/file"
|
||||||
|
class="flex-1 rounded-xl border border-slate-700 bg-slate-950/30 px-3 py-2 text-sm text-slate-100 placeholder-slate-600 focus:outline-none focus:ring-2 focus:ring-cyan-500"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
@click="openPicker"
|
||||||
|
:disabled="remoteSourceConnectionId == null"
|
||||||
|
class="min-h-[44px] px-3 rounded-xl border border-slate-700 bg-slate-900/30 text-slate-200 hover:bg-slate-800/50 disabled:opacity-50 cursor-pointer transition-colors"
|
||||||
|
aria-label="浏览远程文件"
|
||||||
|
>
|
||||||
|
<span class="inline-flex items-center gap-2">
|
||||||
|
<FolderOpen class="w-4 h-4" aria-hidden="true" />
|
||||||
|
浏览
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-3">
|
||||||
|
<label for="remote-target-dir" class="text-sm text-slate-300">目标目录或路径</label>
|
||||||
|
<input
|
||||||
|
id="remote-target-dir"
|
||||||
|
v-model="remoteTargetDirOrPath"
|
||||||
|
type="text"
|
||||||
|
placeholder="/target/dir/"
|
||||||
|
class="w-full rounded-xl border border-slate-700 bg-slate-950/30 px-3 py-2 text-sm text-slate-100 placeholder-slate-600 focus:outline-none focus:ring-2 focus:ring-cyan-500"
|
||||||
|
/>
|
||||||
|
<p class="text-xs text-slate-500">以 / 结尾视为目录,会自动拼接文件名。</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-3">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<label class="text-sm text-slate-300">目标连接</label>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
@click="selectAllRemoteTargets"
|
||||||
|
class="min-h-[44px] px-3 rounded-lg border border-slate-700 bg-slate-900/30 text-slate-200 hover:bg-slate-800/50 transition-colors cursor-pointer text-sm"
|
||||||
|
>
|
||||||
|
全选
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
@click="clearRemoteTargets"
|
||||||
|
class="min-h-[44px] px-3 rounded-lg border border-slate-700 bg-slate-900/30 text-slate-200 hover:bg-slate-800/50 transition-colors cursor-pointer text-sm"
|
||||||
|
>
|
||||||
|
清空
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-2 sm:grid-cols-2">
|
||||||
|
<label
|
||||||
|
v-for="c in remoteTargetConnectionOptions"
|
||||||
|
:key="c.id"
|
||||||
|
class="flex items-center gap-3 rounded-xl border border-slate-800 bg-slate-950/20 px-3 py-2 min-h-[44px] cursor-pointer hover:bg-slate-950/30"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
v-model.number="remoteSelectedTargets"
|
||||||
|
:value="c.id"
|
||||||
|
type="checkbox"
|
||||||
|
class="h-4 w-4 rounded border-slate-600 bg-slate-900 text-cyan-500 focus:ring-cyan-500"
|
||||||
|
/>
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="text-sm text-slate-100 truncate">{{ c.name }}</p>
|
||||||
|
<p class="text-xs text-slate-500 truncate">{{ c.username }}@{{ c.host }}:{{ c.port }}</p>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p v-if="remoteTargetConnectionOptions.length === 0" class="text-xs text-amber-400">
|
||||||
|
没有可用的目标连接(源连接已自动排除)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-2">
|
||||||
|
<label for="remote-concurrency" class="text-sm text-slate-300">并发</label>
|
||||||
|
<input
|
||||||
|
id="remote-concurrency"
|
||||||
|
v-model.number="remoteConcurrency"
|
||||||
|
type="range"
|
||||||
|
min="1"
|
||||||
|
max="6"
|
||||||
|
class="w-full"
|
||||||
|
/>
|
||||||
|
<p class="text-xs text-slate-500">后端是逐个调用 transfer-remote;并发适中即可。</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
@click="startRemote"
|
||||||
|
:disabled="!canStartRemote"
|
||||||
|
class="min-h-[44px] inline-flex items-center justify-center gap-2 rounded-xl bg-cyan-600 px-4 py-2 text-sm font-medium text-white hover:bg-cyan-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
|
aria-label="开始远程转发"
|
||||||
|
>
|
||||||
|
<ArrowUpRight class="w-4 h-4" aria-hidden="true" />
|
||||||
|
开始转发
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<aside class="rounded-2xl border border-slate-800 bg-slate-900/40 backdrop-blur p-5">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<h2 class="text-lg font-semibold text-slate-100">Queue</h2>
|
||||||
|
<span class="text-xs text-slate-500">最近 20 条</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="transfersStore.recentRuns.length === 0" class="mt-4 text-sm text-slate-500">
|
||||||
|
暂无任务。创建一个 plan 然后开始。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else class="mt-4 space-y-3">
|
||||||
|
<div
|
||||||
|
v-for="run in transfersStore.recentRuns"
|
||||||
|
:key="run.id"
|
||||||
|
class="rounded-2xl border border-slate-800 bg-slate-950/20 p-4"
|
||||||
|
>
|
||||||
|
<div class="flex items-start justify-between gap-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="text-sm font-medium text-slate-100 truncate">{{ run.title }}</p>
|
||||||
|
<p class="mt-0.5 text-xs text-slate-500 truncate">{{ new Date(run.createdAt).toLocaleString() }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="text-xs px-2 py-1 rounded-full border" :class="runBadgeClass(run.status)">
|
||||||
|
{{ humanRunStatus(run.status) }}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
v-if="run.status === 'running' || run.status === 'queued'"
|
||||||
|
@click="transfersStore.cancelRun(run.id)"
|
||||||
|
class="w-10 h-10 grid place-items-center rounded-lg border border-slate-800 bg-slate-900/30 text-slate-200 hover:bg-slate-800/50 transition-colors cursor-pointer"
|
||||||
|
aria-label="取消任务"
|
||||||
|
>
|
||||||
|
<XCircle class="w-5 h-5" aria-hidden="true" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-3">
|
||||||
|
<div class="flex items-center justify-between text-xs text-slate-500">
|
||||||
|
<span>{{ run.items.length }} items</span>
|
||||||
|
<span>{{ runProgressPercent(run) }}%</span>
|
||||||
|
</div>
|
||||||
|
<div class="mt-2 w-full h-2 rounded-full bg-slate-800 overflow-hidden">
|
||||||
|
<div
|
||||||
|
class="h-full bg-cyan-500/80 transition-all duration-200"
|
||||||
|
:style="{ width: runProgressPercent(run) + '%' }"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-3 max-h-48 overflow-auto space-y-2">
|
||||||
|
<div
|
||||||
|
v-for="item in run.items"
|
||||||
|
:key="item.id"
|
||||||
|
class="flex items-start gap-2 rounded-xl border border-slate-800 bg-slate-950/10 px-3 py-2"
|
||||||
|
>
|
||||||
|
<Loader2 v-if="item.status === 'running'" class="w-4 h-4 mt-0.5 text-cyan-300 animate-spin" aria-hidden="true" />
|
||||||
|
<CheckCircle2 v-else-if="item.status === 'success'" class="w-4 h-4 mt-0.5 text-emerald-300" aria-hidden="true" />
|
||||||
|
<AlertTriangle v-else-if="item.status === 'error'" class="w-4 h-4 mt-0.5 text-red-300" aria-hidden="true" />
|
||||||
|
<XCircle v-else-if="item.status === 'cancelled'" class="w-4 h-4 mt-0.5 text-slate-300" aria-hidden="true" />
|
||||||
|
<span v-else class="w-4 h-4 mt-0.5 rounded-full bg-amber-400/30" aria-hidden="true" />
|
||||||
|
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="text-xs text-slate-200 truncate">{{ item.label }}</p>
|
||||||
|
<p v-if="item.status === 'running' && item.progress != null" class="mt-1 text-[11px] text-slate-500">
|
||||||
|
{{ item.progress }}%
|
||||||
|
</p>
|
||||||
|
<p v-if="item.status === 'error' && item.message" class="mt-1 text-[11px] text-red-300 break-words">
|
||||||
|
{{ item.message }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<SftpFilePickerModal
|
||||||
|
:open="pickerOpen"
|
||||||
|
:connection-id="remoteSourceConnectionId"
|
||||||
|
@close="pickerOpen = false"
|
||||||
|
@select="(p) => (remoteSourcePath = p)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
Reference in New Issue
Block a user