Compare commits
15 Commits
v1.0.1
...
77518b3f97
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77518b3f97 | ||
|
|
6dbd5ae694 | ||
|
|
e0c734d3d9 | ||
|
|
e2f600c264 | ||
|
|
f892810763 | ||
|
|
c01c005c07 | ||
|
|
c760fbdb85 | ||
|
|
51b479a8f9 | ||
|
|
c387cc2487 | ||
|
|
b0a78fc05a | ||
|
|
80fc5c8a0f | ||
|
|
085123697e | ||
|
|
8845847ce2 | ||
| 939b2ff287 | |||
| e5b9399350 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -13,5 +13,8 @@ frontend/dist/
|
||||
.DS_Store
|
||||
*.local
|
||||
|
||||
# Worktrees
|
||||
.worktrees/
|
||||
|
||||
# Keep frontend .gitignore for frontend-specific rules
|
||||
!frontend/.gitignore
|
||||
|
||||
59
AGENTS.md
59
AGENTS.md
@@ -150,10 +150,65 @@
|
||||
- 检查未提交敏感信息与本地配置
|
||||
- 仅提交与需求直接相关的文件
|
||||
|
||||
## 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`
|
||||
- Copilot 规则:未发现 `.github/copilot-instructions.md`
|
||||
|
||||
若未来新增上述规则文件,agents 必须先读取并将其视为高优先级约束。
|
||||
|
||||
## 11) 近期修复记录
|
||||
|
||||
### 11.1 Docker 启动失败修复
|
||||
|
||||
**问题现象**
|
||||
```text
|
||||
Could not resolve placeholder 'SSHMANAGER_JWT_SECRET'
|
||||
Encryption key must be 32 bytes (256 bits)
|
||||
No qualifying bean of type 'ExecutorService' available: expected single matching bean but found 2
|
||||
```
|
||||
|
||||
**修复措施**
|
||||
1. **`application.yml`** - 为安全配置添加空字符串默认值
|
||||
```yaml
|
||||
sshmanager:
|
||||
encryption-key: ${SSHMANAGER_ENCRYPTION_KEY ""}
|
||||
jwt-secret: ${SSHMANAGER_JWT_SECRET ""}
|
||||
```
|
||||
|
||||
2. **`docker-compose.yml`** - 提供有效的默认密钥(仅用于开发/测试)
|
||||
```yaml
|
||||
environment:
|
||||
- SSHMANAGER_JWT_SECRET=ssh-manager-prod-jwt-secret-20240311
|
||||
- SSHMANAGER_ENCRYPTION_KEY=MLVt7pE35KULIppEiit0doUMvSjozZJ037oNGeXjhVA=
|
||||
```
|
||||
> 注:`MLVt7pE35KULIppEiit0doUMvSjozZJ037oNGeXjhVA=` 是通过 `openssl rand -base64 32` 生成的有效 32 字节 AES-256 密钥
|
||||
|
||||
3. **`TerminalWebSocketHandler.java`** - 解决依赖注入歧义
|
||||
```java
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
|
||||
public TerminalWebSocketHandler(
|
||||
// ... 其他参数
|
||||
@Qualifier("terminalWebSocketExecutor") ExecutorService executor) {
|
||||
}
|
||||
```
|
||||
|
||||
**验证结果**
|
||||
```
|
||||
Started SshManagerApplication in 3.469 seconds (JVM running for 3.836)
|
||||
```
|
||||
|
||||
**注意事项**
|
||||
- **生产环境部署时必须修改** `SSHMANAGER_JWT_SECRET` 和 `SSHMANAGER_ENCRYPTION_KEY`
|
||||
- 建议取消 `docker-compose.yml` 中 `volumes` 注释以持久化 H2 数据库文件
|
||||
|
||||
33
Makefile
Normal file
33
Makefile
Normal file
@@ -0,0 +1,33 @@
|
||||
.PHONY: help build up down restart logs ps
|
||||
|
||||
COMPOSE_FILE := docker/docker-compose.yml
|
||||
COMPOSE := docker compose -f $(COMPOSE_FILE)
|
||||
|
||||
help:
|
||||
@printf "Available targets:\n"
|
||||
@printf " make build Build Docker images\n"
|
||||
@printf " make up Build and start services in background\n"
|
||||
@printf " make down Stop and remove services\n"
|
||||
@printf " make restart Restart services\n"
|
||||
@printf " make logs Follow service logs\n"
|
||||
@printf " make ps Show service status\n"
|
||||
|
||||
build:
|
||||
$(COMPOSE) build
|
||||
|
||||
up:
|
||||
$(COMPOSE) build
|
||||
$(COMPOSE) up -d
|
||||
|
||||
down:
|
||||
$(COMPOSE) down
|
||||
|
||||
restart:
|
||||
$(COMPOSE) down
|
||||
$(COMPOSE) up -d
|
||||
|
||||
logs:
|
||||
$(COMPOSE) logs -f
|
||||
|
||||
ps:
|
||||
$(COMPOSE) ps
|
||||
@@ -67,7 +67,7 @@ ssh-manager/
|
||||
│ ├── components/
|
||||
│ ├── stores/
|
||||
│ └── api/
|
||||
└── design-system/ # UI/UX 规范
|
||||
└── docs/design-system/ # UI/UX 规范
|
||||
```
|
||||
|
||||
## 配置
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.sshmanager.config;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Configuration
|
||||
public class ConfigurationValidator implements CommandLineRunner {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ConfigurationValidator.class);
|
||||
|
||||
@Value("${SSHMANAGER_ENCRYPTION_KEY:}")
|
||||
private String encryptionKey;
|
||||
|
||||
@Value("${SSHMANAGER_JWT_SECRET:}")
|
||||
private String jwtSecret;
|
||||
|
||||
@Override
|
||||
public void run(String... args) {
|
||||
Set<String> missingConfigs = new HashSet<>();
|
||||
|
||||
if (encryptionKey == null || encryptionKey.trim().isEmpty()) {
|
||||
missingConfigs.add("SSHMANAGER_ENCRYPTION_KEY");
|
||||
}
|
||||
if (jwtSecret == null || jwtSecret.trim().isEmpty()) {
|
||||
missingConfigs.add("SSHMANAGER_JWT_SECRET");
|
||||
}
|
||||
|
||||
if (!missingConfigs.isEmpty()) {
|
||||
String missing = String.join(", ", missingConfigs);
|
||||
log.error("Missing required environment variables: {}", missing);
|
||||
log.error("Please set the following environment variables:");
|
||||
missingConfigs.forEach(key -> log.error(" - {} (required)", key));
|
||||
log.error("Application will not start without these configurations.");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
if ("ssh-manager-jwt-secret-change-in-production".equals(jwtSecret)) {
|
||||
log.error("Default JWT secret detected. Please set SSHMANAGER_JWT_SECRET to a secure random value.");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
if (encryptionKey.length() != 44) { // Base64 encoded 32 bytes = 44 chars
|
||||
log.error("Invalid encryption key length. Expected 44 characters (Base64 encoded 32 bytes).");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
log.info("Configuration validation passed.");
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Component
|
||||
public class DataInitializer implements CommandLineRunner {
|
||||
|
||||
@@ -24,6 +26,7 @@ public class DataInitializer implements CommandLineRunner {
|
||||
admin.setUsername("admin");
|
||||
admin.setPasswordHash(passwordEncoder.encode("admin123"));
|
||||
admin.setDisplayName("Administrator");
|
||||
admin.setPasswordChangedAt(Instant.now());
|
||||
userRepository.save(admin);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.sshmanager.config;
|
||||
|
||||
import com.sshmanager.security.JwtAuthenticationFilter;
|
||||
import com.sshmanager.security.PasswordExpirationFilter;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -16,6 +17,8 @@ import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@@ -26,10 +29,14 @@ public class SecurityConfig {
|
||||
@Autowired(required = false)
|
||||
private SecurityExceptionHandler securityExceptionHandler;
|
||||
|
||||
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
|
||||
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter,
|
||||
PasswordExpirationFilter passwordExpirationFilter) {
|
||||
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
|
||||
this.passwordExpirationFilter = passwordExpirationFilter;
|
||||
}
|
||||
|
||||
private final PasswordExpirationFilter passwordExpirationFilter;
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
@@ -49,7 +56,8 @@ public class SecurityConfig {
|
||||
e.authenticationEntryPoint(securityExceptionHandler);
|
||||
}
|
||||
})
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(passwordExpirationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
@@ -62,10 +70,9 @@ public class SecurityConfig {
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
config.setAllowedOrigins(Arrays.asList(
|
||||
"http://localhost:5173", "http://127.0.0.1:5173",
|
||||
"http://localhost:48080", "http://127.0.0.1:48080"
|
||||
));
|
||||
// Docker/remote deployments may be accessed via IP/hostname.
|
||||
// API and WS are still protected by JWT.
|
||||
config.addAllowedOriginPattern("*");
|
||||
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
|
||||
config.setAllowedHeaders(Arrays.asList("*"));
|
||||
config.setAllowCredentials(true);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.sshmanager.config;
|
||||
|
||||
import com.sshmanager.controller.SftpController;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SftpSessionCleanupTask {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SftpSessionCleanupTask.class);
|
||||
|
||||
@Value("${sshmanager.sftp-session-timeout-minutes:30}")
|
||||
private int sessionTimeoutMinutes;
|
||||
|
||||
@Value("${sshmanager.transfer-task-timeout-minutes:30}")
|
||||
private int transferTaskTimeoutMinutes;
|
||||
|
||||
private final SftpController sftpController;
|
||||
|
||||
public SftpSessionCleanupTask(SftpController sftpController) {
|
||||
this.sftpController = sftpController;
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 60000)
|
||||
public void cleanupIdleSessions() {
|
||||
log.debug("Running SFTP session cleanup task");
|
||||
sftpController.cleanupExpiredSessions(sessionTimeoutMinutes);
|
||||
sftpController.cleanupExpiredTransferTasks(transferTaskTimeoutMinutes);
|
||||
}
|
||||
}
|
||||
@@ -23,9 +23,8 @@ public class WebSocketConfig implements WebSocketConfigurer {
|
||||
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
||||
registry.addHandler(terminalWebSocketHandler, "/ws/terminal")
|
||||
.addInterceptors(terminalHandshakeInterceptor)
|
||||
.setAllowedOrigins(
|
||||
"http://localhost:5173", "http://127.0.0.1:5173",
|
||||
"http://localhost:48080", "http://127.0.0.1:48080"
|
||||
);
|
||||
// Docker/remote deployments often use non-localhost origins.
|
||||
// WebSocket access is still protected by JWT in the handshake.
|
||||
.setAllowedOrigins("*");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.sshmanager.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Configuration
|
||||
public class WebSocketThreadPoolConfig {
|
||||
|
||||
@Value("${sshmanager.terminal.websocket.thread-pool.core-size:10}")
|
||||
private int coreSize;
|
||||
|
||||
@Value("${sshmanager.terminal.websocket.thread-pool.max-size:50}")
|
||||
private int maxSize;
|
||||
|
||||
@Value("${sshmanager.terminal.websocket.thread-pool.keep-alive-seconds:60}")
|
||||
private int keepAliveSeconds;
|
||||
|
||||
@Bean
|
||||
public ThreadPoolExecutor terminalWebSocketExecutor() {
|
||||
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
|
||||
ThreadPoolExecutor executor = new ThreadPoolExecutor(
|
||||
coreSize,
|
||||
maxSize,
|
||||
keepAliveSeconds,
|
||||
TimeUnit.SECONDS,
|
||||
queue
|
||||
);
|
||||
return executor;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ScheduledExecutorService websocketCleanupScheduler() {
|
||||
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
||||
scheduler.scheduleAtFixedRate(this::cleanupIdleSessions, 30, 30, TimeUnit.MINUTES);
|
||||
return scheduler;
|
||||
}
|
||||
|
||||
private void cleanupIdleSessions() {
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.sshmanager.controller;
|
||||
|
||||
import com.sshmanager.dto.ConnectionCreateRequest;
|
||||
import com.sshmanager.dto.ConnectionDto;
|
||||
import com.sshmanager.entity.Connection;
|
||||
import com.sshmanager.entity.User;
|
||||
import com.sshmanager.repository.UserRepository;
|
||||
import com.sshmanager.service.ConnectionService;
|
||||
@@ -67,4 +68,27 @@ public class ConnectionController {
|
||||
result.put("message", "Deleted");
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
@PostMapping("/test")
|
||||
public ResponseEntity<Map<String, Object>> connectivity(@RequestBody Connection connection,
|
||||
Authentication authentication) {
|
||||
try {
|
||||
Long userId = getCurrentUserId(authentication);
|
||||
Connection fullConn = connectionService.getConnectionForSsh(connection.getId(), userId);
|
||||
String password = connectionService.getDecryptedPassword(fullConn);
|
||||
String privateKey = connectionService.getDecryptedPrivateKey(fullConn);
|
||||
String passphrase = connectionService.getDecryptedPassphrase(fullConn);
|
||||
|
||||
connectionService.testConnection(fullConn, password, privateKey, passphrase);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("message", "Connection test successful");
|
||||
return ResponseEntity.ok(result);
|
||||
} catch (Exception e) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", false);
|
||||
result.put("message", "Connection failed: " + e.getMessage());
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,20 +9,31 @@ import com.sshmanager.service.ConnectionService;
|
||||
import com.sshmanager.service.SftpService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
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.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
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.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/sftp")
|
||||
@@ -33,20 +44,23 @@ public class SftpController {
|
||||
private final ConnectionService connectionService;
|
||||
private final UserRepository userRepository;
|
||||
private final SftpService sftpService;
|
||||
private final String uploadTempLocation;
|
||||
|
||||
private final Map<String, SftpService.SftpSession> sessions = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* JSch ChannelSftp is not thread-safe. If the frontend triggers concurrent requests (e.g. rapid ".." navigation),
|
||||
* sharing one ChannelSftp can crash with internal stream exceptions. We serialize all SFTP ops per (user, connection).
|
||||
*/
|
||||
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,
|
||||
UserRepository userRepository,
|
||||
SftpService sftpService) {
|
||||
SftpService sftpService,
|
||||
@Value("${spring.servlet.multipart.location:/app/data/upload-temp}") String uploadTempLocation) {
|
||||
this.connectionService = connectionService;
|
||||
this.userRepository = userRepository;
|
||||
this.sftpService = sftpService;
|
||||
this.uploadTempLocation = uploadTempLocation;
|
||||
}
|
||||
|
||||
private Long getCurrentUserId(Authentication auth) {
|
||||
@@ -58,6 +72,14 @@ public class SftpController {
|
||||
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) {
|
||||
Object lock = sessionLocks.computeIfAbsent(key, k -> new Object());
|
||||
synchronized (lock) {
|
||||
@@ -91,6 +113,7 @@ public class SftpController {
|
||||
session = sftpService.connect(conn, password, privateKey, passphrase);
|
||||
sessions.put(key, session);
|
||||
}
|
||||
cleanupTask.recordAccess(key);
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -111,7 +134,6 @@ public class SftpController {
|
||||
.collect(Collectors.toList());
|
||||
return ResponseEntity.ok(dtos);
|
||||
} catch (Exception e) {
|
||||
// If the underlying SFTP channel got into a bad state, force reconnect on next request.
|
||||
SftpService.SftpSession existing = sessions.remove(key);
|
||||
if (existing != null) {
|
||||
existing.disconnect();
|
||||
@@ -132,7 +154,6 @@ public class SftpController {
|
||||
if (e.getMessage() != null && !e.getMessage().trim().isEmpty()) {
|
||||
return e.getMessage();
|
||||
}
|
||||
// Unwrap nested RuntimeExceptions to find the underlying SftpException (if any).
|
||||
Throwable cur = e;
|
||||
for (int i = 0; i < 10 && cur != null; i++) {
|
||||
if (cur instanceof SftpException) {
|
||||
@@ -146,6 +167,64 @@ public class SftpController {
|
||||
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")
|
||||
public ResponseEntity<Map<String, String>> pwd(
|
||||
@RequestParam Long connectionId,
|
||||
@@ -210,36 +289,95 @@ public class SftpController {
|
||||
}
|
||||
|
||||
@PostMapping("/upload")
|
||||
public ResponseEntity<Map<String, String>> upload(
|
||||
public ResponseEntity<Map<String, Object>> upload(
|
||||
@RequestParam Long connectionId,
|
||||
@RequestParam String path,
|
||||
@RequestParam("file") MultipartFile file,
|
||||
Authentication authentication) {
|
||||
java.io.File tempFile = null;
|
||||
try {
|
||||
Long userId = getCurrentUserId(authentication);
|
||||
String taskId = UUID.randomUUID().toString();
|
||||
String taskKey = uploadTaskKey(userId, taskId);
|
||||
|
||||
// Save file to persistent location before async processing
|
||||
java.io.File uploadTempDir = new java.io.File(uploadTempLocation);
|
||||
if (!uploadTempDir.exists() && !uploadTempDir.mkdirs()) {
|
||||
throw new IOException("Failed to create upload temp directory: " + uploadTempDir.getAbsolutePath());
|
||||
}
|
||||
tempFile = new java.io.File(uploadTempDir, taskId + "_" + file.getOriginalFilename());
|
||||
file.transferTo(tempFile);
|
||||
final java.io.File savedFile = tempFile;
|
||||
|
||||
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);
|
||||
return withSessionLock(key, () -> {
|
||||
try {
|
||||
withSessionLock(key, () -> {
|
||||
try {
|
||||
SftpService.SftpSession session = getOrCreateSession(connectionId, userId);
|
||||
String remotePath = (path == null || path.isEmpty() || path.equals("/"))
|
||||
? "/" + file.getOriginalFilename()
|
||||
: (path.endsWith("/") ? path + file.getOriginalFilename() : path + "/" + file.getOriginalFilename());
|
||||
try (java.io.InputStream in = file.getInputStream()) {
|
||||
sftpService.upload(session, remotePath, in);
|
||||
? "/" + savedFile.getName().substring(savedFile.getName().indexOf("_") + 1)
|
||||
: (path.endsWith("/") ? path + savedFile.getName().substring(savedFile.getName().indexOf("_") + 1) : path + "/" + savedFile.getName().substring(savedFile.getName().indexOf("_") + 1));
|
||||
|
||||
AtomicLong transferred = new AtomicLong(0);
|
||||
try (java.io.InputStream in = new java.io.FileInputStream(savedFile)) {
|
||||
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");
|
||||
return ResponseEntity.ok(result);
|
||||
|
||||
@Override
|
||||
public void onProgress(long count, long totalBytes) {
|
||||
long current = transferred.addAndGet(count);
|
||||
status.setProgress(current, status.getTotalBytes());
|
||||
}
|
||||
});
|
||||
}
|
||||
status.markSuccess();
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
SftpService.SftpSession existing = sessions.remove(key);
|
||||
if (existing != null) {
|
||||
existing.disconnect();
|
||||
}
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
// Clean up temp file after upload completes
|
||||
if (savedFile.exists()) {
|
||||
savedFile.delete();
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
Map<String, String> error = new HashMap<>();
|
||||
log.error("Async upload failed, taskId={}, connectionId={}, tempFile={}",
|
||||
taskId, connectionId, savedFile.getAbsolutePath(), e);
|
||||
status.markError(e.getMessage() != null ? e.getMessage() : "Upload failed");
|
||||
// Clean up temp file on error
|
||||
if (savedFile.exists()) {
|
||||
savedFile.delete();
|
||||
}
|
||||
}
|
||||
});
|
||||
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) {
|
||||
log.error("Failed to prepare upload temp file, connectionId={}", connectionId, e);
|
||||
// Clean up temp file if initial save failed
|
||||
if (tempFile != null && tempFile.exists()) {
|
||||
tempFile.delete();
|
||||
}
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("error", e.getMessage());
|
||||
return ResponseEntity.status(500).body(error);
|
||||
}
|
||||
@@ -346,42 +484,13 @@ public class SftpController {
|
||||
Authentication authentication) {
|
||||
try {
|
||||
Long userId = getCurrentUserId(authentication);
|
||||
if (sourcePath == null || sourcePath.trim().isEmpty()) {
|
||||
Map<String, String> err = new HashMap<>();
|
||||
err.put("error", "sourcePath is required");
|
||||
return ResponseEntity.badRequest().body(err);
|
||||
ResponseEntity<Map<String, String>> validation = validateTransferPaths(sourcePath, targetPath);
|
||||
if (validation != null) {
|
||||
return validation;
|
||||
}
|
||||
if (targetPath == null || targetPath.trim().isEmpty()) {
|
||||
Map<String, String> err = new HashMap<>();
|
||||
err.put("error", "targetPath is required");
|
||||
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);
|
||||
}
|
||||
});
|
||||
TransferTaskStatus status = new TransferTaskStatus(UUID.randomUUID().toString(), userId, sourceConnectionId, targetConnectionId,
|
||||
sourcePath.trim(), targetPath.trim());
|
||||
executeTransfer(userId, sourceConnectionId, sourcePath, targetConnectionId, targetPath, status);
|
||||
Map<String, String> result = new HashMap<>();
|
||||
result.put("message", "Transferred");
|
||||
return ResponseEntity.ok(result);
|
||||
@@ -392,6 +501,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")
|
||||
public ResponseEntity<Map<String, String>> disconnect(
|
||||
@RequestParam Long connectionId,
|
||||
@@ -403,8 +712,309 @@ public class SftpController {
|
||||
session.disconnect();
|
||||
}
|
||||
sessionLocks.remove(key);
|
||||
cleanupTask.removeSession(key);
|
||||
Map<String, String> result = new HashMap<>();
|
||||
result.put("message", "Disconnected");
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
public void cleanupExpiredSessions(int timeoutMinutes) {
|
||||
List<String> expired = cleanupTask.getExpiredSessions(timeoutMinutes);
|
||||
for (String key : expired) {
|
||||
SftpService.SftpSession session = sessions.remove(key);
|
||||
if (session != null) {
|
||||
session.disconnect();
|
||||
}
|
||||
sessionLocks.remove(key);
|
||||
cleanupTask.removeSession(key);
|
||||
log.info("Cleaned up expired SFTP session: {}", key);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
public static class SftpSessionExpiryCleanup {
|
||||
private final Map<String, Long> lastAccessTime = new ConcurrentHashMap<>();
|
||||
|
||||
public void recordAccess(String key) {
|
||||
lastAccessTime.put(key, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public void removeSession(String key) {
|
||||
lastAccessTime.remove(key);
|
||||
}
|
||||
|
||||
public List<String> getExpiredSessions(long timeoutMinutes) {
|
||||
long now = System.currentTimeMillis();
|
||||
long timeoutMillis = timeoutMinutes * 60 * 1000;
|
||||
return lastAccessTime.entrySet().stream()
|
||||
.filter(entry -> now - entry.getValue() > timeoutMillis)
|
||||
.map(Map.Entry::getKey)
|
||||
.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.sshmanager.repository.ConnectionRepository;
|
||||
import com.sshmanager.repository.UserRepository;
|
||||
import com.sshmanager.service.ConnectionService;
|
||||
import com.sshmanager.service.SshService;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.CloseStatus;
|
||||
import org.springframework.web.socket.TextMessage;
|
||||
@@ -17,7 +18,7 @@ import java.io.InputStream;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@Component
|
||||
public class TerminalWebSocketHandler extends TextWebSocketHandler {
|
||||
@@ -26,18 +27,22 @@ public class TerminalWebSocketHandler extends TextWebSocketHandler {
|
||||
private final UserRepository userRepository;
|
||||
private final ConnectionService connectionService;
|
||||
private final SshService sshService;
|
||||
private final ExecutorService executor;
|
||||
|
||||
private final ExecutorService executor = Executors.newCachedThreadPool();
|
||||
private final AtomicInteger sessionCount = new AtomicInteger(0);
|
||||
private final Map<String, SshService.SshSession> sessions = new ConcurrentHashMap<>();
|
||||
private final Map<String, Long> lastActivity = new ConcurrentHashMap<>();
|
||||
|
||||
public TerminalWebSocketHandler(ConnectionRepository connectionRepository,
|
||||
UserRepository userRepository,
|
||||
ConnectionService connectionService,
|
||||
SshService sshService) {
|
||||
SshService sshService,
|
||||
@Qualifier("terminalWebSocketExecutor") ExecutorService executor) {
|
||||
this.connectionRepository = connectionRepository;
|
||||
this.userRepository = userRepository;
|
||||
this.connectionService = connectionService;
|
||||
this.sshService = sshService;
|
||||
this.executor = executor;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -69,6 +74,8 @@ public class TerminalWebSocketHandler extends TextWebSocketHandler {
|
||||
try {
|
||||
SshService.SshSession sshSession = sshService.createShellSession(conn, password, privateKey, passphrase);
|
||||
sessions.put(webSocketSession.getId(), sshSession);
|
||||
lastActivity.put(webSocketSession.getId(), System.currentTimeMillis());
|
||||
sessionCount.incrementAndGet();
|
||||
|
||||
executor.submit(() -> {
|
||||
try {
|
||||
@@ -97,6 +104,7 @@ public class TerminalWebSocketHandler extends TextWebSocketHandler {
|
||||
protected void handleTextMessage(WebSocketSession webSocketSession, TextMessage message) throws Exception {
|
||||
SshService.SshSession sshSession = sessions.get(webSocketSession.getId());
|
||||
if (sshSession != null && sshSession.isConnected()) {
|
||||
lastActivity.put(webSocketSession.getId(), System.currentTimeMillis());
|
||||
sshSession.getInputStream().write(message.asBytes());
|
||||
sshSession.getInputStream().flush();
|
||||
}
|
||||
@@ -105,8 +113,10 @@ public class TerminalWebSocketHandler extends TextWebSocketHandler {
|
||||
@Override
|
||||
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus status) throws Exception {
|
||||
SshService.SshSession sshSession = sessions.remove(webSocketSession.getId());
|
||||
lastActivity.remove(webSocketSession.getId());
|
||||
if (sshSession != null) {
|
||||
sshSession.disconnect();
|
||||
sessionCount.decrementAndGet();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import lombok.AllArgsConstructor;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@@ -32,4 +33,7 @@ public class User {
|
||||
|
||||
@Column(nullable = false)
|
||||
private Instant updatedAt = Instant.now();
|
||||
|
||||
@Column(nullable = false)
|
||||
private Instant passwordChangedAt;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.sshmanager.exception;
|
||||
|
||||
public class AccessDeniedException extends SshManagerException {
|
||||
public AccessDeniedException(String message) {
|
||||
super(403, "ACCESS_DENIED", message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.sshmanager.exception;
|
||||
|
||||
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
import org.springframework.web.multipart.MultipartException;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(MaxUploadSizeExceededException.class)
|
||||
public ResponseEntity<Map<String, String>> handleMaxUploadSize(MaxUploadSizeExceededException e) {
|
||||
Map<String, String> err = new HashMap<>();
|
||||
err.put("error", "上传失败:文件大小超过限制");
|
||||
return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).body(err);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MultipartException.class)
|
||||
public ResponseEntity<Map<String, String>> handleMultipart(MultipartException e) {
|
||||
Throwable root = e;
|
||||
while (root.getCause() != null && root.getCause() != root) {
|
||||
root = root.getCause();
|
||||
}
|
||||
|
||||
if (root instanceof FileSizeLimitExceededException
|
||||
|| (root.getMessage() != null && root.getMessage().contains("exceeds its maximum permitted size"))) {
|
||||
Map<String, String> err = new HashMap<>();
|
||||
err.put("error", "上传失败:文件大小超过限制");
|
||||
return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).body(err);
|
||||
}
|
||||
|
||||
Map<String, String> err = new HashMap<>();
|
||||
err.put("error", "上传失败:表单解析异常");
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(err);
|
||||
}
|
||||
|
||||
@ExceptionHandler(SshManagerException.class)
|
||||
public ResponseEntity<Map<String, Object>> handleSshManagerException(SshManagerException e) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("error", e.getErrorCode());
|
||||
error.put("message", e.getMessage());
|
||||
return ResponseEntity.status(e.getStatusCode()).body(error);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<Map<String, Object>> handleException(Exception e) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("error", "INTERNAL_ERROR");
|
||||
error.put("message", "Internal server error");
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.sshmanager.exception;
|
||||
|
||||
public class InvalidOperationException extends SshManagerException {
|
||||
public InvalidOperationException(String message) {
|
||||
super(400, "INVALID_OPERATION", message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.sshmanager.exception;
|
||||
|
||||
public class NotFoundException extends SshManagerException {
|
||||
public NotFoundException(String message) {
|
||||
super(404, "NOT_FOUND", message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.sshmanager.exception;
|
||||
|
||||
public class SshManagerException extends RuntimeException {
|
||||
private final int statusCode;
|
||||
private final String errorCode;
|
||||
|
||||
public SshManagerException(int statusCode, String errorCode, String message) {
|
||||
super(message);
|
||||
this.statusCode = statusCode;
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
public String getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.sshmanager.exception;
|
||||
|
||||
public class UnauthorizedException extends SshManagerException {
|
||||
public UnauthorizedException(String message) {
|
||||
super(401, "UNAUTHORIZED", message);
|
||||
}
|
||||
}
|
||||
@@ -52,8 +52,9 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
|
||||
return bearerToken.substring(7);
|
||||
}
|
||||
// WebSocket handshake sends token as query param
|
||||
if (request.getRequestURI() != null && request.getRequestURI().startsWith("/ws/")) {
|
||||
// WebSocket handshake and SSE endpoints send token as query param
|
||||
String uri = request.getRequestURI();
|
||||
if (uri != null && (uri.startsWith("/ws/") || uri.contains("/progress"))) {
|
||||
String token = request.getParameter("token");
|
||||
if (StringUtils.hasText(token)) {
|
||||
return token;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.sshmanager.security;
|
||||
|
||||
import com.sshmanager.entity.User;
|
||||
import com.sshmanager.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
@Component
|
||||
public class PasswordExpirationFilter extends OncePerRequestFilter {
|
||||
|
||||
@Value("${sshmanager.password-expiration-days:90}")
|
||||
private int passwordExpirationDays;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public PasswordExpirationFilter(UserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.isAuthenticated()) {
|
||||
String username = authentication.getName();
|
||||
User user = userRepository.findByUsername(username).orElse(null);
|
||||
if (user != null && isPasswordExpired(user)) {
|
||||
request.setAttribute("passwordExpired", true);
|
||||
}
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private boolean isPasswordExpired(User user) {
|
||||
Instant passwordChangedAt = user.getPasswordChangedAt();
|
||||
if (passwordChangedAt == null) {
|
||||
return true;
|
||||
}
|
||||
return passwordChangedAt.isBefore(Instant.now().minus(passwordExpirationDays, ChronoUnit.DAYS));
|
||||
}
|
||||
}
|
||||
@@ -16,11 +16,14 @@ public class ConnectionService {
|
||||
|
||||
private final ConnectionRepository connectionRepository;
|
||||
private final EncryptionService encryptionService;
|
||||
private final SshService sshService;
|
||||
|
||||
public ConnectionService(ConnectionRepository connectionRepository,
|
||||
EncryptionService encryptionService) {
|
||||
EncryptionService encryptionService,
|
||||
SshService sshService) {
|
||||
this.connectionRepository = connectionRepository;
|
||||
this.encryptionService = encryptionService;
|
||||
this.sshService = sshService;
|
||||
}
|
||||
|
||||
public List<ConnectionDto> listByUserId(Long userId) {
|
||||
@@ -130,4 +133,18 @@ public class ConnectionService {
|
||||
return conn.getPassphrase() != null ?
|
||||
encryptionService.decrypt(conn.getPassphrase()) : null;
|
||||
}
|
||||
|
||||
public Connection testConnection(Connection conn, String password, String privateKey, String passphrase) {
|
||||
SshService.SshSession session = null;
|
||||
try {
|
||||
session = sshService.createShellSession(conn, password, privateKey, passphrase);
|
||||
return conn;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Connection test failed: " + e.getMessage(), e);
|
||||
} finally {
|
||||
if (session != null) {
|
||||
session.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,9 @@ package com.sshmanager.service;
|
||||
import com.jcraft.jsch.ChannelSftp;
|
||||
import com.jcraft.jsch.JSch;
|
||||
import com.jcraft.jsch.Session;
|
||||
import com.jcraft.jsch.SftpATTRS;
|
||||
import com.jcraft.jsch.SftpException;
|
||||
import com.jcraft.jsch.SftpProgressMonitor;
|
||||
import com.sshmanager.entity.Connection;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -15,16 +17,20 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Vector;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@Service
|
||||
public class SftpService {
|
||||
|
||||
private ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
|
||||
public void setExecutorService(ExecutorService executorService) {
|
||||
this.executorService = executorService;
|
||||
}
|
||||
|
||||
public SftpSession connect(Connection conn, String password, String privateKey, String passphrase)
|
||||
throws Exception {
|
||||
JSch jsch = new JSch();
|
||||
@@ -40,8 +46,14 @@ public class SftpService {
|
||||
session.setConfig("StrictHostKeyChecking", "no");
|
||||
// Use only DH-based kex to avoid "Algorithm ECDH not available" on Java 8 / minimal JRE
|
||||
session.setConfig("kex", "diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1");
|
||||
if (conn.getAuthType() == Connection.AuthType.PASSWORD && password != null) {
|
||||
if (conn.getAuthType() == Connection.AuthType.PASSWORD) {
|
||||
if (password == null || password.isEmpty()) {
|
||||
throw new IllegalArgumentException("Password is required for password authentication");
|
||||
}
|
||||
session.setConfig("PreferredAuthentications", "password");
|
||||
session.setPassword(password);
|
||||
} else {
|
||||
session.setConfig("PreferredAuthentications", "publickey");
|
||||
}
|
||||
session.connect(10000);
|
||||
|
||||
@@ -92,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 {
|
||||
String listPath = (path == null || path.trim().isEmpty()) ? "." : path.trim();
|
||||
try {
|
||||
@@ -156,6 +174,30 @@ public class SftpService {
|
||||
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 {
|
||||
if (isDir) {
|
||||
sftpSession.getChannel().rmdir(remotePath);
|
||||
@@ -186,38 +228,69 @@ public class SftpService {
|
||||
*/
|
||||
public void transferRemote(SftpSession source, String sourcePath, SftpSession target, String targetPath)
|
||||
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");
|
||||
}
|
||||
final long totalBytes = attrs.getSize();
|
||||
final int pipeBufferSize = 65536;
|
||||
PipedOutputStream pos = new PipedOutputStream();
|
||||
PipedInputStream pis = new PipedInputStream(pos, pipeBufferSize);
|
||||
AtomicLong transferredBytes = new AtomicLong(0);
|
||||
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
if (progressListener != null) {
|
||||
progressListener.onStart(totalBytes);
|
||||
}
|
||||
|
||||
Future<?> putFuture = executorService.submit(() -> {
|
||||
try {
|
||||
Future<?> putFuture = executor.submit(() -> {
|
||||
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) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
try {
|
||||
source.getChannel().get(sourcePath, pos);
|
||||
pos.close();
|
||||
putFuture.get(5, TimeUnit.MINUTES);
|
||||
} catch (ExecutionException e) {
|
||||
Throwable cause = e.getCause();
|
||||
if (cause instanceof RuntimeException && cause.getCause() instanceof Exception) {
|
||||
throw (Exception) cause.getCause();
|
||||
}
|
||||
if (cause instanceof Exception) {
|
||||
throw (Exception) cause;
|
||||
}
|
||||
throw new RuntimeException(cause);
|
||||
} catch (TimeoutException e) {
|
||||
throw new RuntimeException("Transfer timeout", e);
|
||||
} finally {
|
||||
executor.shutdownNow();
|
||||
try {
|
||||
pos.close();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
putFuture.get();
|
||||
} finally {
|
||||
try {
|
||||
pis.close();
|
||||
} catch (Exception ignored) {
|
||||
|
||||
@@ -31,8 +31,14 @@ public class SshService {
|
||||
// Use only DH-based kex to avoid "Algorithm ECDH not available" on Java 8 / minimal JRE
|
||||
session.setConfig("kex", "diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1");
|
||||
|
||||
if (conn.getAuthType() == Connection.AuthType.PASSWORD && password != null) {
|
||||
if (conn.getAuthType() == Connection.AuthType.PASSWORD) {
|
||||
if (password == null || password.isEmpty()) {
|
||||
throw new IllegalArgumentException("Password is required for password authentication");
|
||||
}
|
||||
session.setConfig("PreferredAuthentications", "password");
|
||||
session.setPassword(password);
|
||||
} else {
|
||||
session.setConfig("PreferredAuthentications", "publickey");
|
||||
}
|
||||
|
||||
session.connect(10000);
|
||||
|
||||
@@ -5,6 +5,12 @@ spring:
|
||||
web:
|
||||
resources:
|
||||
add-mappings: false # 使用 SpaForwardConfig 统一处理静态与 SPA 回退
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 2048MB
|
||||
max-request-size: 2048MB
|
||||
location: ${DATA_DIR:/app/data}/upload-temp # 使用容器数据目录,避免被解析为 Tomcat 工作目录
|
||||
file-size-threshold: 0 # 立即写入磁盘,不使用内存缓冲
|
||||
datasource:
|
||||
url: jdbc:h2:file:./data/sshmanager;DB_CLOSE_DELAY=-1
|
||||
driver-class-name: org.h2.Driver
|
||||
@@ -13,6 +19,9 @@ spring:
|
||||
h2:
|
||||
console:
|
||||
enabled: false
|
||||
path: /h2
|
||||
settings:
|
||||
web-allow-others: true
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: update
|
||||
@@ -25,6 +34,13 @@ spring:
|
||||
|
||||
# Encryption key for connection passwords (base64, 32 bytes for AES-256)
|
||||
sshmanager:
|
||||
encryption-key: ${SSHMANAGER_ENCRYPTION_KEY:YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoxMjM0NTY=}
|
||||
jwt-secret: ${SSHMANAGER_JWT_SECRET:ssh-manager-jwt-secret-change-in-production}
|
||||
encryption-key: ${SSHMANAGER_ENCRYPTION_KEY ""}
|
||||
jwt-secret: ${SSHMANAGER_JWT_SECRET ""}
|
||||
jwt-expiration-ms: 86400000
|
||||
password-expiration-days: ${SSHMANAGER_PASSWORD_EXPIRATION_DAYS:90}
|
||||
terminal:
|
||||
websocket:
|
||||
thread-pool:
|
||||
core-size: 10
|
||||
max-size: 50
|
||||
keep-alive-seconds: 60
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.sshmanager.controller;
|
||||
|
||||
import com.sshmanager.entity.Connection;
|
||||
import com.sshmanager.entity.User;
|
||||
import com.sshmanager.repository.UserRepository;
|
||||
import com.sshmanager.service.ConnectionService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ConnectionControllerTest {
|
||||
|
||||
@Mock
|
||||
private ConnectionService connectionService;
|
||||
|
||||
@Mock
|
||||
private UserRepository userRepository;
|
||||
|
||||
@InjectMocks
|
||||
private ConnectionController connectionController;
|
||||
|
||||
private Authentication authentication;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
authentication = mock(Authentication.class);
|
||||
when(authentication.getName()).thenReturn("testuser");
|
||||
User user = new User();
|
||||
user.setId(1L);
|
||||
when(userRepository.findByUsername("testuser")).thenReturn(Optional.of(user));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConnectivityWithValidConnection() {
|
||||
Long connectionId = 1L;
|
||||
Connection conn = new Connection();
|
||||
conn.setId(connectionId);
|
||||
conn.setHost("127.0.0.1");
|
||||
conn.setPort(22);
|
||||
conn.setUsername("root");
|
||||
conn.setAuthType(Connection.AuthType.PASSWORD);
|
||||
conn.setUserId(1L);
|
||||
|
||||
when(connectionService.getConnectionForSsh(connectionId, 1L)).thenReturn(conn);
|
||||
when(connectionService.getDecryptedPassword(conn)).thenReturn("password");
|
||||
|
||||
ResponseEntity<?> response = connectionController.connectivity(conn, authentication);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> body = (Map<String, Object>) response.getBody();
|
||||
assertTrue((Boolean) body.get("success"));
|
||||
assertEquals("Connection test successful", body.get("message"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConnectivityWithConnectionFailure() {
|
||||
Long connectionId = 1L;
|
||||
Connection conn = new Connection();
|
||||
conn.setId(connectionId);
|
||||
conn.setHost("127.0.0.1");
|
||||
conn.setPort(22);
|
||||
conn.setUsername("root");
|
||||
conn.setAuthType(Connection.AuthType.PASSWORD);
|
||||
conn.setUserId(1L);
|
||||
|
||||
when(connectionService.getConnectionForSsh(connectionId, 1L)).thenReturn(conn);
|
||||
when(connectionService.getDecryptedPassword(conn)).thenReturn("password");
|
||||
doThrow(new RuntimeException("Connection refused")).when(connectionService).testConnection(conn, "password", null, null);
|
||||
|
||||
ResponseEntity<?> response = connectionController.connectivity(conn, authentication);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> body = (Map<String, Object>) response.getBody();
|
||||
assertFalse((Boolean) body.get("success"));
|
||||
assertTrue(((String) body.get("message")).contains("Connection failed"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.sshmanager.service;
|
||||
|
||||
import com.sshmanager.entity.Connection;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SftpServiceTest {
|
||||
|
||||
private SftpService sftpService;
|
||||
private ExecutorService executorService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
executorService = Executors.newFixedThreadPool(2);
|
||||
sftpService = new SftpService();
|
||||
sftpService.setExecutorService(executorService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPasswordAuthenticationRequiredWithValidConnection() {
|
||||
Exception exception = assertThrows(Exception.class, () -> {
|
||||
Connection conn = new Connection();
|
||||
conn.setHost("127.0.0.1");
|
||||
conn.setPort(22);
|
||||
conn.setUsername("test");
|
||||
conn.setAuthType(Connection.AuthType.PASSWORD);
|
||||
sftpService.connect(conn, "", null, null);
|
||||
});
|
||||
assertTrue(exception.getMessage().contains("Password is required") ||
|
||||
exception instanceof IllegalArgumentException);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPasswordAuthenticationRequiredWithNullConn() {
|
||||
Exception exception = assertThrows(Exception.class, () -> {
|
||||
sftpService.connect(null, "", null, null);
|
||||
});
|
||||
assertTrue(exception instanceof NullPointerException || exception instanceof IllegalArgumentException);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExecutorServiceShutdown() throws Exception {
|
||||
executorService.shutdown();
|
||||
assertTrue(executorService.isTerminated() || executorService.isShutdown());
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -41,7 +41,7 @@ WORKDIR /app
|
||||
COPY --from=backend /build/target/*.jar app.jar
|
||||
|
||||
ENV DATA_DIR=/app/data
|
||||
RUN mkdir -p ${DATA_DIR}
|
||||
RUN mkdir -p ${DATA_DIR}/upload-temp
|
||||
|
||||
EXPOSE 48080
|
||||
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
在**项目根目录**执行:
|
||||
|
||||
```bash
|
||||
# 一键(推荐)
|
||||
make up
|
||||
|
||||
# 构建镜像
|
||||
docker compose -f docker/docker-compose.yml build
|
||||
|
||||
@@ -22,6 +25,14 @@ docker compose -f docker/docker-compose.yml up
|
||||
docker compose -f docker/docker-compose.yml up -d
|
||||
```
|
||||
|
||||
常用命令:
|
||||
|
||||
```bash
|
||||
make logs # 查看日志
|
||||
make ps # 查看状态
|
||||
make down # 停止并移除容器
|
||||
```
|
||||
|
||||
访问:http://localhost:48080
|
||||
|
||||
## 环境变量(可选)
|
||||
|
||||
@@ -13,9 +13,10 @@ services:
|
||||
- "48080:48080"
|
||||
environment:
|
||||
- TZ=Asia/Shanghai
|
||||
# 生产环境建议设置并挂载密钥
|
||||
# - SSHMANAGER_ENCRYPTION_KEY=...
|
||||
# - SSHMANAGER_JWT_SECRET=...
|
||||
# JWT Secret (change in production!)
|
||||
- SSHMANAGER_JWT_SECRET=ssh-manager-prod-jwt-secret-20240311
|
||||
# Encryption Key (base64, 32 bytes; change in production!)
|
||||
- SSHMANAGER_ENCRYPTION_KEY=MLVt7pE35KULIppEiit0doUMvSjozZJ037oNGeXjhVA=
|
||||
volumes:
|
||||
- app-data:/app/data
|
||||
restart: unless-stopped
|
||||
|
||||
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" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<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>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
13
frontend/package-lock.json
generated
13
frontend/package-lock.json
generated
@@ -15,6 +15,7 @@
|
||||
"pinia": "^3.0.4",
|
||||
"vue": "^3.5.24",
|
||||
"vue-router": "^5.0.2",
|
||||
"vue-toast-notification": "^3.1.3",
|
||||
"xterm": "^5.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -3327,6 +3328,18 @@
|
||||
"integrity": "sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vue-toast-notification": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmmirror.com/vue-toast-notification/-/vue-toast-notification-3.1.3.tgz",
|
||||
"integrity": "sha512-XNyWqwLIGBFfX5G9sK+clq3N3IPlhDjzNdbZaXkEElcotPlWs0wWZailk1vqhdtLYT/93Y4FHAVuzyatLmPZRA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.15.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vue-tsc": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-3.2.4.tgz",
|
||||
|
||||
@@ -16,15 +16,16 @@
|
||||
"pinia": "^3.0.4",
|
||||
"vue": "^3.5.24",
|
||||
"vue-router": "^5.0.2",
|
||||
"vue-toast-notification": "^3.1.3",
|
||||
"xterm": "^5.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.10.1",
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"@vue/tsconfig": "^0.8.1",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"postcss": "^8.4.47",
|
||||
"tailwindcss": "^3.4.14",
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"@vue/tsconfig": "^0.8.1",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^7.2.4",
|
||||
"vue-tsc": "^3.1.4"
|
||||
|
||||
@@ -12,6 +12,19 @@ client.interceptors.request.use((config) => {
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
|
||||
// Let the browser set the correct multipart boundary.
|
||||
if (typeof FormData !== 'undefined' && config.data instanceof FormData) {
|
||||
const headers: any = config.headers ?? {}
|
||||
if (typeof headers.set === 'function') {
|
||||
headers.set('Content-Type', undefined)
|
||||
} else {
|
||||
delete headers['Content-Type']
|
||||
delete headers['content-type']
|
||||
}
|
||||
config.headers = headers
|
||||
}
|
||||
|
||||
return config
|
||||
})
|
||||
|
||||
|
||||
@@ -7,6 +7,18 @@ export interface SftpFileInfo {
|
||||
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) {
|
||||
return client.get<SftpFileInfo[]>('/sftp/list', {
|
||||
params: { connectionId, path: path || '.' },
|
||||
@@ -37,15 +49,73 @@ export async function downloadFile(connectionId: number, path: string) {
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
export function uploadFileWithProgress(connectionId: number, path: string, file: File) {
|
||||
const token = localStorage.getItem('token')
|
||||
const url = `/api/sftp/upload?connectionId=${connectionId}&path=${encodeURIComponent(path)}`
|
||||
const xhr = new XMLHttpRequest()
|
||||
const form = new FormData()
|
||||
form.append('file', file, file.name)
|
||||
|
||||
xhr.open('POST', url)
|
||||
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) => {
|
||||
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)
|
||||
console.log('[Upload Progress] percent:', percent, 'hasCallback:', !!wrapper.onProgress)
|
||||
if (wrapper.onProgress) wrapper.onProgress(percent)
|
||||
}
|
||||
|
||||
// Defer send so callers can attach onload/onerror/onProgress safely.
|
||||
setTimeout(() => {
|
||||
try {
|
||||
xhr.send(form)
|
||||
} 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) {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
return client.post('/sftp/upload', form, {
|
||||
form.append('file', file, file.name)
|
||||
return client.post<{ taskId: string; message: string }>('/sftp/upload', form, {
|
||||
params: { connectionId, path },
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
}
|
||||
|
||||
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) {
|
||||
return client.delete('/sftp/delete', {
|
||||
params: { connectionId, path, directory },
|
||||
@@ -79,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)}`
|
||||
)
|
||||
}
|
||||
|
||||
@@ -20,10 +20,32 @@ const username = ref('')
|
||||
const authType = ref<AuthType>('PASSWORD')
|
||||
const password = ref('')
|
||||
const privateKey = ref('')
|
||||
const privateKeyFileName = ref('')
|
||||
const privateKeyInputRef = ref<HTMLInputElement | null>(null)
|
||||
const passphrase = ref('')
|
||||
|
||||
const isEdit = computed(() => !!props.connection)
|
||||
|
||||
const hostError = computed(() => {
|
||||
const h = host.value.trim()
|
||||
if (!h) return ''
|
||||
const ipv4Regex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/
|
||||
const hostnameRegex = /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/
|
||||
if (ipv4Regex.test(h)) {
|
||||
const parts = h.match(ipv4Regex)
|
||||
if (parts && parts.slice(1, 5).every(p => parseInt(p) <= 255)) return ''
|
||||
return 'IP地址格式无效'
|
||||
}
|
||||
if (hostnameRegex.test(h)) return ''
|
||||
return '主机名格式无效'
|
||||
})
|
||||
|
||||
const portError = computed(() => {
|
||||
const p = port.value
|
||||
if (p < 1 || p > 65535) return '端口号必须在1-65535之间'
|
||||
return ''
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.connection,
|
||||
(c) => {
|
||||
@@ -35,6 +57,7 @@ watch(
|
||||
authType.value = c.authType
|
||||
password.value = ''
|
||||
privateKey.value = ''
|
||||
privateKeyFileName.value = ''
|
||||
passphrase.value = ''
|
||||
} else {
|
||||
name.value = ''
|
||||
@@ -44,6 +67,7 @@ watch(
|
||||
authType.value = 'PASSWORD'
|
||||
password.value = ''
|
||||
privateKey.value = ''
|
||||
privateKeyFileName.value = ''
|
||||
passphrase.value = ''
|
||||
}
|
||||
},
|
||||
@@ -52,9 +76,69 @@ watch(
|
||||
|
||||
const error = ref('')
|
||||
const loading = ref(false)
|
||||
const backdropPressed = ref(false)
|
||||
|
||||
function handleBackdropMouseDown() {
|
||||
backdropPressed.value = true
|
||||
}
|
||||
|
||||
function handleBackdropMouseUp() {
|
||||
if (backdropPressed.value) {
|
||||
emit('close')
|
||||
}
|
||||
backdropPressed.value = false
|
||||
}
|
||||
|
||||
function handleDialogMouseDown() {
|
||||
backdropPressed.value = false
|
||||
}
|
||||
|
||||
function normalizeKeyText(text: string) {
|
||||
return text.replace(/\r\n?/g, '\n').trim() + '\n'
|
||||
}
|
||||
|
||||
async function handlePrivateKeyFileChange(e: Event) {
|
||||
error.value = ''
|
||||
const input = e.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
if (!file) return
|
||||
|
||||
// Keep it generous; OpenSSH keys are usually a few KB.
|
||||
const MAX_SIZE = 256 * 1024
|
||||
if (file.size > MAX_SIZE) {
|
||||
error.value = '私钥文件过大(>256KB),请检查是否选错文件'
|
||||
input.value = ''
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const text = await file.text()
|
||||
privateKey.value = normalizeKeyText(text)
|
||||
privateKeyFileName.value = file.name
|
||||
} catch {
|
||||
error.value = '读取私钥文件失败'
|
||||
input.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function clearPrivateKeyFile() {
|
||||
privateKey.value = ''
|
||||
privateKeyFileName.value = ''
|
||||
if (privateKeyInputRef.value) privateKeyInputRef.value.value = ''
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
error.value = ''
|
||||
const hostErr = hostError.value
|
||||
const portErr = portError.value
|
||||
if (hostErr) {
|
||||
error.value = hostErr
|
||||
return
|
||||
}
|
||||
if (portErr) {
|
||||
error.value = portErr
|
||||
return
|
||||
}
|
||||
if (!name.value.trim()) {
|
||||
error.value = '请填写名称'
|
||||
return
|
||||
@@ -108,12 +192,17 @@ async function handleSubmit() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" @click.self="emit('close')">
|
||||
<div
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
|
||||
@mousedown.self="handleBackdropMouseDown"
|
||||
@mouseup.self="handleBackdropMouseUp"
|
||||
>
|
||||
<div
|
||||
class="w-full max-w-lg bg-slate-800 rounded-xl border border-slate-700 shadow-xl"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="form-title"
|
||||
@mousedown="handleDialogMouseDown"
|
||||
>
|
||||
<div class="flex items-center justify-between p-4 border-b border-slate-700">
|
||||
<h2 id="form-title" class="text-lg font-semibold text-slate-100">
|
||||
@@ -148,6 +237,7 @@ async function handleSubmit() {
|
||||
class="w-full px-4 py-2.5 rounded-lg bg-slate-700 border border-slate-600 text-slate-100 focus:outline-none focus:ring-2 focus:ring-cyan-500"
|
||||
placeholder="192.168.1.1"
|
||||
/>
|
||||
<p v-if="hostError" class="mt-1 text-xs text-red-400">{{ hostError }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label for="port" class="block text-sm font-medium text-slate-300 mb-1">端口</label>
|
||||
@@ -159,6 +249,7 @@ async function handleSubmit() {
|
||||
max="65535"
|
||||
class="w-full px-4 py-2.5 rounded-lg bg-slate-700 border border-slate-600 text-slate-100 focus:outline-none focus:ring-2 focus:ring-cyan-500"
|
||||
/>
|
||||
<p v-if="portError" class="mt-1 text-xs text-red-400">{{ portError }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
@@ -200,13 +291,24 @@ async function handleSubmit() {
|
||||
<label for="privateKey" class="block text-sm font-medium text-slate-300 mb-1">
|
||||
私钥 {{ isEdit ? '(留空则不修改)' : '' }}
|
||||
</label>
|
||||
<textarea
|
||||
<input
|
||||
ref="privateKeyInputRef"
|
||||
id="privateKey"
|
||||
v-model="privateKey"
|
||||
rows="6"
|
||||
class="w-full px-4 py-2.5 rounded-lg bg-slate-700 border border-slate-600 text-slate-100 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-cyan-500"
|
||||
placeholder="-----BEGIN OPENSSH PRIVATE KEY----- ... -----END OPENSSH PRIVATE KEY-----"
|
||||
></textarea>
|
||||
type="file"
|
||||
accept=".pem,.key,.ppk,.txt,application/x-pem-file"
|
||||
class="w-full px-4 py-2.5 rounded-lg bg-slate-700 border border-slate-600 text-slate-100 focus:outline-none focus:ring-2 focus:ring-cyan-500 file:mr-4 file:rounded-md file:border-0 file:bg-slate-600 file:px-3 file:py-2 file:text-slate-100 hover:file:bg-slate-500"
|
||||
@change="handlePrivateKeyFileChange"
|
||||
/>
|
||||
<div v-if="privateKeyFileName" class="flex items-center justify-between gap-3">
|
||||
<p class="text-xs text-slate-400 truncate">已选择:{{ privateKeyFileName }}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-slate-300 hover:text-slate-100 hover:underline"
|
||||
@click="clearPrivateKeyFile"
|
||||
>
|
||||
清除
|
||||
</button>
|
||||
</div>
|
||||
<label for="passphrase" class="block text-sm font-medium text-slate-300 mb-1">私钥口令(可选)</label>
|
||||
<input
|
||||
id="passphrase"
|
||||
|
||||
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>
|
||||
@@ -1,20 +1,36 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { RouterLink, useRoute } from 'vue-router'
|
||||
import { ref, computed } from 'vue'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '../stores/auth'
|
||||
import { useConnectionsStore } from '../stores/connections'
|
||||
import { Server, LogOut, Menu, X } from 'lucide-vue-next'
|
||||
import { useTerminalTabsStore } from '../stores/terminalTabs'
|
||||
import { ArrowLeftRight, Server, LogOut, Menu, X, Terminal } from 'lucide-vue-next'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const authStore = useAuthStore()
|
||||
const connectionsStore = useConnectionsStore()
|
||||
const tabsStore = useTerminalTabsStore()
|
||||
const sidebarOpen = ref(false)
|
||||
|
||||
const terminalTabs = computed(() => tabsStore.tabs)
|
||||
|
||||
connectionsStore.fetchConnections().catch(() => {})
|
||||
|
||||
function closeSidebar() {
|
||||
sidebarOpen.value = false
|
||||
}
|
||||
|
||||
function handleTabClick(tabId: string) {
|
||||
tabsStore.activate(tabId)
|
||||
router.push('/terminal')
|
||||
closeSidebar()
|
||||
}
|
||||
|
||||
function handleTabClose(tabId: string, event: Event) {
|
||||
event.stopPropagation()
|
||||
tabsStore.close(tabId)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -35,10 +51,20 @@ function closeSidebar() {
|
||||
]"
|
||||
>
|
||||
<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>
|
||||
</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 overflow-y-auto">
|
||||
<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
|
||||
to="/connections"
|
||||
@click="closeSidebar"
|
||||
@@ -49,6 +75,32 @@ function closeSidebar() {
|
||||
<Server class="w-5 h-5 flex-shrink-0" aria-hidden="true" />
|
||||
<span>连接列表</span>
|
||||
</RouterLink>
|
||||
|
||||
<!-- 终端标签区域 -->
|
||||
<div v-if="terminalTabs.length > 0" class="pt-4 mt-4 border-t border-slate-700">
|
||||
<div class="flex items-center gap-2 px-3 py-2 text-xs font-semibold text-slate-500 uppercase tracking-wider">
|
||||
<Terminal class="w-4 h-4" aria-hidden="true" />
|
||||
<span>终端</span>
|
||||
</div>
|
||||
<div class="space-y-1 mt-2">
|
||||
<button
|
||||
v-for="tab in terminalTabs"
|
||||
:key="tab.id"
|
||||
@click="handleTabClick(tab.id)"
|
||||
class="w-full flex items-center justify-between gap-2 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 group"
|
||||
:class="{ 'bg-slate-700 text-cyan-400': tab.active && route.path === '/terminal' }"
|
||||
>
|
||||
<span class="truncate text-sm">{{ tab.title }}</span>
|
||||
<button
|
||||
@click="(e) => handleTabClose(tab.id, e)"
|
||||
class="p-1 rounded opacity-0 group-hover:opacity-100 hover:bg-slate-600 transition-all duration-200 flex-shrink-0"
|
||||
aria-label="关闭标签"
|
||||
>
|
||||
<X class="w-3 h-3" aria-hidden="true" />
|
||||
</button>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
<div class="p-4 border-t border-slate-700">
|
||||
<button
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import Toast from 'vue-toast-notification'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import './style.css'
|
||||
@@ -7,4 +8,9 @@ import './style.css'
|
||||
const app = createApp(App)
|
||||
app.use(createPinia())
|
||||
app.use(router)
|
||||
app.use(Toast, {
|
||||
position: 'top-right',
|
||||
duration: 3000,
|
||||
dismissible: true,
|
||||
})
|
||||
app.mount('#app')
|
||||
|
||||
@@ -19,11 +19,21 @@ const routes: RouteRecordRaw[] = [
|
||||
name: 'Home',
|
||||
redirect: '/connections',
|
||||
},
|
||||
{
|
||||
path: 'transfers',
|
||||
name: 'Transfers',
|
||||
component: () => import('../views/TransfersView.vue'),
|
||||
},
|
||||
{
|
||||
path: 'connections',
|
||||
name: 'Connections',
|
||||
component: () => import('../views/ConnectionsView.vue'),
|
||||
},
|
||||
{
|
||||
path: 'terminal',
|
||||
name: 'TerminalWorkspace',
|
||||
component: () => import('../views/TerminalWorkspaceView.vue'),
|
||||
},
|
||||
{
|
||||
path: 'terminal/:id',
|
||||
name: 'Terminal',
|
||||
|
||||
74
frontend/src/stores/terminalTabs.ts
Normal file
74
frontend/src/stores/terminalTabs.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import type { Connection } from '../api/connections'
|
||||
|
||||
export interface TerminalTab {
|
||||
id: string
|
||||
connectionId: number
|
||||
title: string
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export const useTerminalTabsStore = defineStore('terminalTabs', () => {
|
||||
const tabs = ref<TerminalTab[]>([])
|
||||
const activeTabId = ref<string | null>(null)
|
||||
|
||||
const activeTab = computed(() => tabs.value.find(t => t.id === activeTabId.value) || null)
|
||||
|
||||
function generateTabId() {
|
||||
return `tab-${Date.now()}-${Math.random().toString(16).slice(2)}`
|
||||
}
|
||||
|
||||
function openOrFocus(connection: Connection) {
|
||||
// 检查是否已存在该连接的标签页
|
||||
const existing = tabs.value.find(t => t.connectionId === connection.id)
|
||||
if (existing) {
|
||||
activate(existing.id)
|
||||
return existing.id
|
||||
}
|
||||
|
||||
// 创建新标签页
|
||||
const newTab: TerminalTab = {
|
||||
id: generateTabId(),
|
||||
connectionId: connection.id,
|
||||
title: connection.name,
|
||||
active: true,
|
||||
}
|
||||
|
||||
tabs.value.push(newTab)
|
||||
activate(newTab.id)
|
||||
return newTab.id
|
||||
}
|
||||
|
||||
function activate(tabId: string) {
|
||||
tabs.value.forEach(t => {
|
||||
t.active = t.id === tabId
|
||||
})
|
||||
activeTabId.value = tabId
|
||||
}
|
||||
|
||||
function close(tabId: string) {
|
||||
const index = tabs.value.findIndex(t => t.id === tabId)
|
||||
if (index === -1) return
|
||||
|
||||
const wasActive = tabs.value[index]!.active
|
||||
tabs.value.splice(index, 1)
|
||||
|
||||
// 如果关闭的是活动标签,激活相邻标签
|
||||
if (wasActive && tabs.value.length > 0) {
|
||||
const newIndex = Math.min(index, tabs.value.length - 1)
|
||||
activate(tabs.value[newIndex]!.id)
|
||||
} else if (tabs.value.length === 0) {
|
||||
activeTabId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
tabs,
|
||||
activeTabId,
|
||||
activeTab,
|
||||
openOrFocus,
|
||||
activate,
|
||||
close,
|
||||
}
|
||||
})
|
||||
379
frontend/src/stores/transfers.ts
Normal file
379
frontend/src/stores/transfers.ts
Normal file
@@ -0,0 +1,379 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
import { createRemoteTransferTask, subscribeRemoteTransferProgress, uploadFile, subscribeUploadProgress } 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]
|
||||
|
||||
let cancelled = false
|
||||
const unsubscribers: (() => void)[] = []
|
||||
controllers.set(runId, {
|
||||
abortAll: () => {
|
||||
cancelled = true
|
||||
},
|
||||
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' || cancelled) return
|
||||
item.status = 'running'
|
||||
item.progress = 0
|
||||
item.startedAt = now()
|
||||
runs.value = [...runs.value]
|
||||
const stopPseudoProgress = startPseudoProgress(item)
|
||||
|
||||
try {
|
||||
// 发起上传并获取 taskId
|
||||
const uploadRes = await uploadFile(connectionId, targetDir || '', file)
|
||||
const taskId = uploadRes.data.taskId
|
||||
|
||||
// 订阅上传任务进度,等待真正完成
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const unsubscribe = subscribeUploadProgress(taskId, (task) => {
|
||||
const progress = Math.max(0, Math.min(100, task.progress || 0))
|
||||
item.progress = progress
|
||||
runs.value = [...runs.value]
|
||||
|
||||
if (task.status === 'success') {
|
||||
resolve()
|
||||
} else if (task.status === 'error') {
|
||||
reject(new Error(task.error || 'Upload failed'))
|
||||
}
|
||||
})
|
||||
unsubscribers.push(unsubscribe)
|
||||
})
|
||||
|
||||
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;
|
||||
|
||||
@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 {
|
||||
@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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useConnectionsStore } from '../stores/connections'
|
||||
import { useTerminalTabsStore } from '../stores/terminalTabs'
|
||||
import type { Connection, ConnectionCreateRequest } from '../api/connections'
|
||||
import ConnectionForm from '../components/ConnectionForm.vue'
|
||||
import {
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
|
||||
const router = useRouter()
|
||||
const store = useConnectionsStore()
|
||||
const tabsStore = useTerminalTabsStore()
|
||||
|
||||
const showForm = ref(false)
|
||||
const editingConn = ref<Connection | null>(null)
|
||||
@@ -53,7 +55,8 @@ async function handleDelete(conn: Connection) {
|
||||
}
|
||||
|
||||
function openTerminal(conn: Connection) {
|
||||
router.push(`/terminal/${conn.id}`)
|
||||
tabsStore.openOrFocus(conn)
|
||||
router.push('/terminal')
|
||||
}
|
||||
|
||||
function openSftp(conn: Connection) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useToast } from 'vue-toast-notification'
|
||||
import { useConnectionsStore } from '../stores/connections'
|
||||
import * as sftpApi from '../api/sftp'
|
||||
import type { SftpFileInfo } from '../api/sftp'
|
||||
@@ -11,14 +12,20 @@ import {
|
||||
Upload,
|
||||
FolderPlus,
|
||||
RefreshCw,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Download,
|
||||
Trash2,
|
||||
ChevronRight,
|
||||
Copy,
|
||||
CheckCircle,
|
||||
AlertCircle,
|
||||
Loader,
|
||||
} from 'lucide-vue-next'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const store = useConnectionsStore()
|
||||
|
||||
const connectionId = computed(() => Number(route.params.id))
|
||||
@@ -33,12 +40,129 @@ const uploading = ref(false)
|
||||
const selectedFile = ref<string | null>(null)
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null)
|
||||
|
||||
const showHiddenFiles = ref(false)
|
||||
const searchQuery = ref('')
|
||||
let searchDebounceTimer = 0
|
||||
const filteredFiles = ref<SftpFileInfo[]>([])
|
||||
|
||||
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 })
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearTimeout(searchDebounceTimer)
|
||||
stopTransferProgress()
|
||||
})
|
||||
|
||||
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 totalProgress = computed(() => {
|
||||
if (uploadProgressList.value.length === 0) return 0
|
||||
const totalSize = uploadProgressList.value.reduce((sum, item) => sum + item.size, 0)
|
||||
const uploadedSize = uploadProgressList.value.reduce((sum, item) => {
|
||||
if (item.status === 'success') return sum + item.size
|
||||
if (item.status === 'uploading') return sum + item.uploaded
|
||||
return sum
|
||||
}, 0)
|
||||
return totalSize > 0 ? Math.round((uploadedSize / totalSize) * 100) : 0
|
||||
})
|
||||
|
||||
const currentUploadingFile = computed(() => {
|
||||
return uploadProgressList.value.find(item => item.status === 'uploading')?.name || ''
|
||||
})
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return bytes + ' B'
|
||||
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
|
||||
return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
|
||||
}
|
||||
|
||||
function formatDate(ts: number): string {
|
||||
return new Date(ts).toLocaleString()
|
||||
}
|
||||
|
||||
const showTransferModal = ref(false)
|
||||
const transferFile = ref<SftpFileInfo | null>(null)
|
||||
const transferTargetConnectionId = ref<number | null>(null)
|
||||
const transferTargetPath = ref('')
|
||||
const transferring = ref(false)
|
||||
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(() => {
|
||||
conn.value = store.getConnection(connectionId.value)
|
||||
@@ -55,7 +179,7 @@ onMounted(() => {
|
||||
function initPath() {
|
||||
sftpApi.getPwd(connectionId.value).then((res) => {
|
||||
const p = res.data.path || '/'
|
||||
currentPath.value = p || '.'
|
||||
currentPath.value = p === '/' ? '/' : p
|
||||
pathParts.value = p === '/' ? [''] : p.split('/').filter(Boolean)
|
||||
loadPath()
|
||||
}).catch((err: { response?: { data?: { error?: string } } }) => {
|
||||
@@ -86,6 +210,7 @@ function loadPath() {
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -93,6 +218,7 @@ function navigateToDir(name: string) {
|
||||
}
|
||||
|
||||
function navigateToIndex(i: number) {
|
||||
if (loading.value) return
|
||||
if (i < 0) {
|
||||
currentPath.value = '.'
|
||||
} else {
|
||||
@@ -103,6 +229,7 @@ function navigateToIndex(i: number) {
|
||||
}
|
||||
|
||||
function goUp() {
|
||||
if (loading.value) return
|
||||
if (currentPath.value === '.' || currentPath.value === '' || currentPath.value === '/') {
|
||||
return
|
||||
}
|
||||
@@ -146,19 +273,77 @@ async function handleFileSelect(e: Event) {
|
||||
uploading.value = true
|
||||
error.value = ''
|
||||
const path = currentPath.value === '.' ? '' : currentPath.value
|
||||
try {
|
||||
|
||||
const uploadTasks: { id: string; file: File; taskId?: string }[] = []
|
||||
for (let i = 0; i < selected.length; i++) {
|
||||
const file = selected[i]
|
||||
if (!file) continue
|
||||
await sftpApi.uploadFile(connectionId.value, path, file)
|
||||
uploadTasks.push({ id: `${Date.now()}-${i}`, file })
|
||||
}
|
||||
loadPath()
|
||||
} catch {
|
||||
error.value = '上传失败'
|
||||
} finally {
|
||||
|
||||
uploadProgressList.value = uploadTasks.map(({ id, file }) => ({
|
||||
id,
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
uploaded: 0,
|
||||
total: file.size,
|
||||
status: 'pending',
|
||||
}))
|
||||
|
||||
showUploadProgress.value = true
|
||||
|
||||
const MAX_PARALLEL = 5
|
||||
|
||||
for (let i = 0; i < uploadTasks.length; i += MAX_PARALLEL) {
|
||||
const batch = uploadTasks.slice(i, i + MAX_PARALLEL)
|
||||
const batchPromises = batch.map(async task => {
|
||||
if (!task) return
|
||||
const { id, file } = task
|
||||
const item = uploadProgressList.value.find(item => item.id === id)
|
||||
if (!item) return
|
||||
|
||||
item.status = 'uploading'
|
||||
|
||||
try {
|
||||
// Start upload and get taskId
|
||||
const uploadRes = await sftpApi.uploadFile(connectionId.value, path, file)
|
||||
const taskId = uploadRes.data.taskId
|
||||
|
||||
// Poll for progress
|
||||
while (true) {
|
||||
const statusRes = await sftpApi.getUploadTask(taskId)
|
||||
const taskStatus = statusRes.data
|
||||
|
||||
item.uploaded = taskStatus.transferredBytes
|
||||
item.total = taskStatus.totalBytes
|
||||
|
||||
if (taskStatus.status === 'success') {
|
||||
item.status = 'success'
|
||||
break
|
||||
}
|
||||
if (taskStatus.status === 'error') {
|
||||
item.status = 'error'
|
||||
item.message = taskStatus.error || 'Upload failed'
|
||||
break
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 200))
|
||||
}
|
||||
} catch (err: any) {
|
||||
item.status = 'error'
|
||||
item.message = err?.response?.data?.error || 'Upload failed'
|
||||
}
|
||||
})
|
||||
await Promise.allSettled(batchPromises)
|
||||
}
|
||||
|
||||
await loadPath()
|
||||
const successCount = uploadProgressList.value.filter(item => item.status === 'success').length
|
||||
showUploadProgress.value = false
|
||||
uploadProgressList.value = []
|
||||
uploading.value = false
|
||||
input.value = ''
|
||||
}
|
||||
fileInputRef.value!.value = ''
|
||||
toast.success(`成功上传 ${successCount} 个文件`)
|
||||
}
|
||||
|
||||
function handleMkdir() {
|
||||
@@ -197,11 +382,14 @@ async function openTransferModal(file: SftpFileInfo) {
|
||||
}
|
||||
|
||||
function closeTransferModal() {
|
||||
if (transferring.value) return
|
||||
stopTransferProgress()
|
||||
showTransferModal.value = false
|
||||
transferFile.value = null
|
||||
transferTargetConnectionId.value = null
|
||||
transferTargetPath.value = ''
|
||||
transferError.value = ''
|
||||
resetTransferProgress()
|
||||
}
|
||||
|
||||
async function submitTransfer() {
|
||||
@@ -214,27 +402,21 @@ async function submitTransfer() {
|
||||
if (targetPath.endsWith('/') || !targetPath) targetPath = targetPath + file.name
|
||||
transferring.value = true
|
||||
transferError.value = ''
|
||||
resetTransferProgress()
|
||||
try {
|
||||
await sftpApi.transferRemote(connectionId.value, sourcePath, targetId, targetPath)
|
||||
loadPath()
|
||||
const created = await sftpApi.createRemoteTransferTask(connectionId.value, sourcePath, targetId, targetPath)
|
||||
await waitForTransferTask(created.data.taskId)
|
||||
transferProgress.value = 100
|
||||
await loadPath()
|
||||
closeTransferModal()
|
||||
} catch (err: unknown) {
|
||||
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 {
|
||||
stopTransferProgress()
|
||||
transferring.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return bytes + ' B'
|
||||
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
|
||||
return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
|
||||
}
|
||||
|
||||
function formatDate(ts: number): string {
|
||||
return new Date(ts).toLocaleString()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -254,8 +436,8 @@ function formatDate(ts: number): string {
|
||||
|
||||
<div class="flex-1 overflow-auto p-4">
|
||||
<div class="bg-slate-800 rounded-xl border border-slate-700 overflow-hidden">
|
||||
<div class="flex items-center gap-2 p-3 border-b border-slate-700 bg-slate-800/80">
|
||||
<nav class="flex items-center gap-1 text-sm text-slate-400 min-w-0 flex-1">
|
||||
<div class="flex flex-col sm:flex-row sm:items-center gap-2 p-3 border-b border-slate-700 bg-slate-800/80">
|
||||
<nav class="flex items-center gap-1 text-sm text-slate-400 min-w-0 w-full sm:flex-1">
|
||||
<button
|
||||
@click="navigateToIndex(-1)"
|
||||
class="px-2 py-1 rounded hover:bg-slate-700 hover:text-slate-100 transition-colors duration-200 cursor-pointer truncate"
|
||||
@@ -272,7 +454,24 @@ function formatDate(ts: number): string {
|
||||
</button>
|
||||
</template>
|
||||
</nav>
|
||||
<div class="flex items-center gap-1 flex-shrink-0">
|
||||
<div class="w-full sm:w-auto flex items-center gap-2 justify-end">
|
||||
<div class="flex-1 sm:flex-none">
|
||||
<input
|
||||
v-model="searchQuery"
|
||||
type="text"
|
||||
class="w-full sm:w-56 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="搜索文件"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
@click="showHiddenFiles = !showHiddenFiles"
|
||||
class="p-2 rounded-lg text-slate-400 hover:bg-slate-700 hover:text-slate-100 transition-colors duration-200 cursor-pointer"
|
||||
:aria-label="showHiddenFiles ? '隐藏隐藏文件' : '显示隐藏文件'"
|
||||
:title="showHiddenFiles ? '隐藏隐藏文件' : '显示隐藏文件'"
|
||||
>
|
||||
<component :is="showHiddenFiles ? EyeOff : Eye" class="w-4 h-4" aria-hidden="true" />
|
||||
</button>
|
||||
<button
|
||||
@click="triggerUpload"
|
||||
:disabled="uploading"
|
||||
@@ -306,6 +505,41 @@ function formatDate(ts: number): string {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="showUploadProgress" class="bg-slate-800/50 border-b border-slate-700 p-4 space-y-3">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-sm text-slate-300">上传进度: {{ totalProgress }}%</span>
|
||||
<span class="text-sm text-slate-400">{{ currentUploadingFile || '准备上传...' }}</span>
|
||||
</div>
|
||||
<div class="w-full bg-slate-700 rounded-full h-2 overflow-hidden">
|
||||
<div
|
||||
class="bg-cyan-600 h-full transition-all duration-300"
|
||||
:style="{ width: totalProgress + '%' }"
|
||||
></div>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 gap-2 max-h-40 overflow-y-auto">
|
||||
<div
|
||||
v-for="item in uploadProgressList"
|
||||
:key="item.id"
|
||||
class="flex items-center gap-3 text-sm"
|
||||
>
|
||||
<CheckCircle v-if="item.status === 'success'" class="w-4 h-4 flex-shrink-0 text-green-500" aria-hidden="true" />
|
||||
<AlertCircle v-else-if="item.status === 'error'" class="w-4 h-4 flex-shrink-0 text-red-500" aria-hidden="true" />
|
||||
<Loader v-else-if="item.status === 'uploading'" class="w-4 h-4 flex-shrink-0 text-cyan-500 animate-spin" aria-hidden="true" />
|
||||
<File v-else class="w-4 h-4 flex-shrink-0 text-slate-500" aria-hidden="true" />
|
||||
<span class="flex-1 truncate text-slate-300">{{ item.name }}</span>
|
||||
<span class="text-slate-400 text-xs">
|
||||
{{ formatSize(item.size) }}
|
||||
<template v-if="item.status === 'uploading'">
|
||||
({{ Math.round((item.uploaded / item.total) * 100) }}%)
|
||||
</template>
|
||||
<template v-else-if="item.status === 'success'">
|
||||
✓
|
||||
</template>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="px-4 py-2 text-sm text-red-400">{{ error }}</p>
|
||||
|
||||
<div v-if="loading" class="p-8 text-center text-slate-400">
|
||||
@@ -322,10 +556,10 @@ function formatDate(ts: number): string {
|
||||
<span class="text-slate-400">..</span>
|
||||
</button>
|
||||
<button
|
||||
v-for="file in files"
|
||||
v-for="file in filteredFiles"
|
||||
:key="file.name"
|
||||
@click="handleFileClick(file)"
|
||||
@dblclick="file.directory ? navigateToDir(file.name) : handleDownload(file)"
|
||||
@dblclick="!file.directory && handleDownload(file)"
|
||||
class="w-full flex items-center gap-3 px-4 py-3 hover:bg-slate-700/50 transition-colors duration-200 cursor-pointer text-left group"
|
||||
>
|
||||
<component
|
||||
@@ -364,8 +598,8 @@ function formatDate(ts: number): string {
|
||||
</button>
|
||||
</div>
|
||||
</button>
|
||||
<div v-if="files.length === 0 && !loading" class="p-8 text-center text-slate-500">
|
||||
空目录
|
||||
<div v-if="filteredFiles.length === 0 && !loading" class="p-8 text-center text-slate-500">
|
||||
{{ files.length === 0 ? '空目录' : (searchQuery.trim() ? '未找到匹配文件' : '无可见文件(已隐藏文件)') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -414,14 +648,29 @@ function formatDate(ts: number): string {
|
||||
</div>
|
||||
</div>
|
||||
<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">
|
||||
<button
|
||||
type="button"
|
||||
@click="closeTransferModal"
|
||||
:disabled="transferring"
|
||||
class="rounded-lg border border-slate-600 px-4 py-2 text-slate-300 hover:bg-slate-700 disabled:opacity-50 cursor-pointer"
|
||||
@click="transferring ? cancelTransfer() : closeTransferModal()"
|
||||
class="rounded-lg border border-slate-600 px-4 py-2 text-slate-300 hover:bg-slate-700 cursor-pointer"
|
||||
>
|
||||
取消
|
||||
{{ transferring ? '取消传输' : '取消' }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,46 +1,37 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useConnectionsStore } from '../stores/connections'
|
||||
import TerminalWidget from '../components/TerminalWidget.vue'
|
||||
import { ArrowLeft } from 'lucide-vue-next'
|
||||
import { useTerminalTabsStore } from '../stores/terminalTabs'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = useConnectionsStore()
|
||||
const connectionsStore = useConnectionsStore()
|
||||
const tabsStore = useTerminalTabsStore()
|
||||
|
||||
const connectionId = computed(() => Number(route.params.id))
|
||||
const conn = ref(store.getConnection(connectionId.value))
|
||||
|
||||
onMounted(() => {
|
||||
conn.value = store.getConnection(connectionId.value)
|
||||
if (!conn.value) {
|
||||
store.fetchConnections().then(() => {
|
||||
conn.value = store.getConnection(connectionId.value)
|
||||
})
|
||||
onMounted(async () => {
|
||||
// 确保连接列表已加载
|
||||
if (connectionsStore.connections.length === 0) {
|
||||
await connectionsStore.fetchConnections()
|
||||
}
|
||||
|
||||
const conn = connectionsStore.getConnection(connectionId.value)
|
||||
if (conn) {
|
||||
// 打开或聚焦该连接的标签页
|
||||
tabsStore.openOrFocus(conn)
|
||||
// 跳转到工作区
|
||||
router.replace('/terminal')
|
||||
} else {
|
||||
// 连接不存在,返回连接列表
|
||||
router.replace('/connections')
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="h-full flex flex-col">
|
||||
<div class="flex items-center gap-4 p-4 border-b border-slate-700 bg-slate-800/50">
|
||||
<button
|
||||
@click="router.push('/connections')"
|
||||
class="p-2 rounded-lg text-slate-400 hover:bg-slate-700 hover:text-slate-100 transition-colors duration-200 cursor-pointer"
|
||||
aria-label="返回"
|
||||
>
|
||||
<ArrowLeft class="w-5 h-5" aria-hidden="true" />
|
||||
</button>
|
||||
<h2 class="text-lg font-semibold text-slate-100">
|
||||
{{ conn?.name || '终端' }} - {{ conn?.username }}@{{ conn?.host }}
|
||||
</h2>
|
||||
</div>
|
||||
<div class="flex-1 min-h-0 p-4">
|
||||
<TerminalWidget v-if="conn" :connection-id="conn.id" />
|
||||
<div v-else class="flex items-center justify-center h-64 text-slate-400">
|
||||
加载中...
|
||||
</div>
|
||||
</div>
|
||||
<div class="h-full flex items-center justify-center text-slate-400">
|
||||
正在打开终端...
|
||||
</div>
|
||||
</template>
|
||||
|
||||
42
frontend/src/views/TerminalWorkspaceView.vue
Normal file
42
frontend/src/views/TerminalWorkspaceView.vue
Normal file
@@ -0,0 +1,42 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { useTerminalTabsStore } from '../stores/terminalTabs'
|
||||
import { useConnectionsStore } from '../stores/connections'
|
||||
import TerminalWidget from '../components/TerminalWidget.vue'
|
||||
|
||||
const tabsStore = useTerminalTabsStore()
|
||||
const connectionsStore = useConnectionsStore()
|
||||
|
||||
const tabs = computed(() => tabsStore.tabs)
|
||||
|
||||
onMounted(() => {
|
||||
// 确保连接列表已加载
|
||||
if (connectionsStore.connections.length === 0) {
|
||||
connectionsStore.fetchConnections()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="h-full flex flex-col">
|
||||
<!-- 终端内容区 -->
|
||||
<div class="flex-1 min-h-0 p-4">
|
||||
<div v-if="tabs.length === 0" class="flex items-center justify-center h-full text-slate-400">
|
||||
<div class="text-center">
|
||||
<p class="text-lg mb-2">暂无打开的终端</p>
|
||||
<p class="text-sm text-slate-500">从左侧连接列表点击"终端"按钮打开</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="h-full">
|
||||
<div
|
||||
v-for="tab in tabs"
|
||||
:key="tab.id"
|
||||
v-show="tab.active"
|
||||
class="h-full"
|
||||
>
|
||||
<TerminalWidget :connection-id="tab.connectionId" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
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>
|
||||
@@ -12,5 +12,5 @@
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "src/**/*.d.ts"]
|
||||
}
|
||||
|
||||
6
package-lock.json
generated
Normal file
6
package-lock.json
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "fix-transfer-and-multi-terminal",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {}
|
||||
}
|
||||
Reference in New Issue
Block a user