This commit is contained in:
Baobhan Sith
2025-05-07 19:25:45 +08:00
parent 7510747359
commit 6ba859227d
21 changed files with 983 additions and 181 deletions
@@ -30,7 +30,7 @@ const { isLoading: isSshKeyLoading, error: sshKeyStoreError } = storeToRefs(sshK
// 表单数据模型
const initialFormData = {
type: 'SSH' as 'SSH' | 'RDP', // Use uppercase to match ConnectionInfo
type: 'SSH' as 'SSH' | 'RDP' | 'VNC', // Use uppercase to match ConnectionInfo
name: '',
host: '',
port: 22,
@@ -42,7 +42,8 @@ const initialFormData = {
selected_ssh_key_id: null as number | null, // +++ Add field for selected key ID +++
proxy_id: null as number | null,
tag_ids: [] as number[], // 新增 tag_ids 字段
notes: '', // 新增备注字段
notes: '', // 新增备注字段
vncPassword: '', // VNC specific password
// Add RDP specific fields later if needed, e.g., domain
};
const formData = reactive({ ...initialFormData });
@@ -79,7 +80,7 @@ watch(() => props.connectionToEdit, (newVal) => {
formError.value = null; // 清除错误
if (newVal) {
// 编辑模式:填充表单,但不填充敏感信息
formData.type = newVal.type; // Correctly set the type for editing
formData.type = newVal.type as 'SSH' | 'RDP' | 'VNC'; // Correctly set the type for editing
formData.name = newVal.name;
formData.host = newVal.host;
formData.port = newVal.port;
@@ -90,23 +91,34 @@ formData.notes = newVal.notes ?? ''; // 填充备注
formData.tag_ids = newVal.tag_ids ? [...newVal.tag_ids] : []; // 填充 tag_ids (深拷贝)
// +++ 填充 selected_ssh_key_id (如果认证方式是 key) +++
if (newVal.auth_method === 'key') {
if (newVal.type === 'SSH' && newVal.auth_method === 'key') {
formData.selected_ssh_key_id = newVal.ssh_key_id ?? null;
} else {
formData.selected_ssh_key_id = null; // 清空,以防之前是 key
formData.selected_ssh_key_id = null; // 清空
}
// 清空敏感字段
formData.password = ''; // For SSH/RDP
formData.private_key = '';
formData.passphrase = '';
// formData.vncPassword is already handled by initialFormData or cleared if not VNC
if (newVal.type !== 'VNC') {
formData.vncPassword = '';
} else {
// If editing a VNC connection, we don't get vncPassword from backend directly.
// User needs to re-enter if they want to change it.
// For display, it's kept empty.
formData.vncPassword = '';
}
// 清空敏感字段 (密码和直接输入的密钥)
formData.password = '';
formData.private_key = ''; // 即使是 key 认证,编辑时也不显示旧的直接输入密钥
formData.passphrase = ''; // 同上
} else {
// 添加模式:重置表单
Object.assign(formData, initialFormData);
formData.tag_ids = []; // 确保 tag_ids 也被重置为空数组
formData.selected_ssh_key_id = null; // 确保添加模式下也重置
formData.notes = ''; // 重置备注
formData.notes = ''; // 重置备注
formData.vncPassword = ''; // 重置VNC密码
}
}, { immediate: true });
@@ -120,15 +132,17 @@ onMounted(() => {
// 监听连接类型变化,动态调整默认端口
watch(() => formData.type, (newType) => {
// Use uppercase for comparison
if (newType === 'RDP' && formData.port === 22) {
formData.port = 3389; // RDP 默认端口
} else if (newType === 'SSH' && formData.port === 3389) {
formData.port = 22; // SSH 默认端口
}
// 重置或调整认证方式等逻辑可以在这里添加
if (newType === 'RDP') {
// RDP 通常只用密码,可以强制或隐藏 auth_method
// formData.auth_method = 'password'; // Example: Force password for RDP
if (formData.port === 22 || formData.port === 5900 || formData.port === 5901) formData.port = 3389; // RDP 默认端口
formData.auth_method = 'password'; // RDP uses password
formData.selected_ssh_key_id = null; // Clear SSH key selection
} else if (newType === 'SSH') {
if (formData.port === 3389 || formData.port === 5900 || formData.port === 5901) formData.port = 22; // SSH 默认端口
// auth_method will be handled by its own select
} else if (newType === 'VNC') {
if (formData.port === 22 || formData.port === 3389) formData.port = 5900; // VNC 默认端口 (e.g., 5900 or 5901)
formData.auth_method = 'password'; // VNC uses password, hide auth_method selector
formData.selected_ssh_key_id = null; // Clear SSH key selection
}
});
@@ -190,11 +204,18 @@ const handleSubmit = async () => {
// RDP Validation
// 1. 添加模式下,密码是必填的
if (!isEditMode.value && !formData.password) {
formError.value = t('connections.form.errorPasswordRequired'); // 可以复用密码必填的翻译
formError.value = t('connections.form.errorPasswordRequired');
return;
}
// 2. 编辑模式下,密码可以不填(表示不修改),除非是从非 RDP 类型切换过来(这个逻辑比较复杂,暂时简化为密码非必填)
// 如果需要更严格的验证(例如从 SSH 编辑为 RDP 时强制要求输入密码),可以在这里添加
// 2. 编辑模式下,密码可以不填(表示不修改)
} else if (formData.type === 'VNC') {
// VNC Validation
// 1. 添加模式下,VNC密码是必填的
if (!isEditMode.value && !formData.vncPassword) {
formError.value = t('connections.form.errorVncPasswordRequired', 'VNC 密码是必填项。'); // Add new translation key
return;
}
// 2. 编辑模式下,VNC密码可以不填(表示不修改)
}
// --- 验证逻辑结束 ---
@@ -256,6 +277,21 @@ notes: formData.notes, // 添加备注
delete dataToSend.auth_method;
delete dataToSend.private_key;
delete dataToSend.passphrase;
delete dataToSend.vncPassword; // Ensure VNC password field for form doesn't go if RDP
} else if (formData.type === 'VNC') {
// VNC data population
if (formData.vncPassword) {
dataToSend.password = formData.vncPassword; // Backend expects VNC password in 'password' field
} else if (isEditMode.value && formData.vncPassword === '') {
// Editing VNC, empty password means don't change
}
// VNC does not use SSH specific fields
delete dataToSend.auth_method;
delete dataToSend.private_key;
delete dataToSend.passphrase;
delete dataToSend.ssh_key_id;
// formData.vncPassword is used for the form, but backend might expect it as 'password'
// So, we don't send 'vncPassword' itself to backend.
}
@@ -424,6 +460,7 @@ const testButtonText = computed(() => {
style="background-image: url('data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 16 16\'%3e%3cpath fill=\'none\' stroke=\'%236c757d\' stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M2 5l6 6 6-6\'/%3e%3c/svg%3e'); background-position: right 0.75rem center; background-size: 16px 12px;">
<option value="SSH">{{ t('connections.form.typeSsh', 'SSH') }}</option>
<option value="RDP">{{ t('connections.form.typeRdp', 'RDP') }}</option>
<option value="VNC">{{ t('connections.form.typeVnc', 'VNC') }}</option>
</select>
</div>
<!-- Host and Port Row -->
@@ -498,13 +535,22 @@ const testButtonText = computed(() => {
class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary" />
-->
</div>
</template>
<!-- VNC Specific Auth (Password only) -->
<template v-if="formData.type === 'VNC'">
<div>
<label for="conn-password-vnc" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.vncPassword', 'VNC 密码') }}</label>
<input type="password" id="conn-password-vnc" v-model="formData.vncPassword" :required="!isEditMode" autocomplete="new-password"
class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary" />
</div>
</template>
</div>
</div>
<!-- Advanced Options Section -->
<div class="space-y-4 p-4 border border-border rounded-md bg-header/30">
<h4 class="text-base font-semibold mb-3 pb-2 border-b border-border/50">{{ t('connections.form.sectionAdvanced', '高级选项') }}</h4>
<div v-if="formData.type !== 'RDP'"> <!-- Proxy Select - Hide for RDP -->
<div v-if="formData.type === 'SSH'"> <!-- Proxy Select - Show only for SSH -->
<label for="conn-proxy" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.proxy') }} ({{ t('connections.form.optional') }})</label>
<select id="conn-proxy" v-model="formData.proxy_id"
class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary appearance-none bg-no-repeat bg-right pr-8"
@@ -551,7 +597,6 @@ const testButtonText = computed(() => {
<!-- Form Actions -->
<div class="flex justify-between items-center pt-5 mt-6 flex-shrink-0">
<!-- Test Area (Only show for SSH) -->
<!-- Use uppercase for comparison -->
<div v-if="formData.type === 'SSH'" class="flex flex-col items-start gap-1">
<div class="flex items-center gap-2"> <!-- Button and Icon -->
<button type="button" @click="handleTestConnection" :disabled="isLoading || testStatus === 'testing'"
@@ -583,7 +628,7 @@ const testButtonText = computed(() => {
</div>
</div>
<!-- Placeholder for alignment when test button is hidden -->
<div v-else class="flex-1"></div>
<div v-else class="flex-1"></div> <!-- This div ensures the main action buttons are pushed to the right when test area is hidden -->
<div class="flex space-x-3"> <!-- Main Actions -->
<button type="submit" @click="handleSubmit" :disabled="isLoading || (formData.type === 'SSH' && testStatus === 'testing')"
class="px-4 py-2 bg-button text-button-text rounded-md shadow-sm hover:bg-button-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed transition duration-150 ease-in-out">
@@ -182,7 +182,7 @@ const handleDelete = async (conn: ConnectionInfo) => {
<tbody class="divide-y divide-border">
<tr v-for="conn in groupConnections" :key="conn.id" class="hover:bg-hover transition-colors duration-150">
<td class="px-4 py-3 text-sm text-foreground whitespace-nowrap flex items-center">
<i :class="['fas', conn.type === 'RDP' ? 'fa-desktop' : 'fa-server', 'mr-2 w-4 text-center text-text-secondary']"></i>
<i :class="['fas', conn.type === 'RDP' || conn.type === 'VNC' ? 'fa-desktop' : 'fa-server', 'mr-2 w-4 text-center text-text-secondary']"></i>
<span>{{ conn.name }}</span>
</td>
<td class="px-4 py-3 text-sm text-foreground whitespace-nowrap">{{ conn.host }}</td>
@@ -2,6 +2,7 @@
import { ref, onMounted, onUnmounted, watch, nextTick, computed, watchEffect } from 'vue';
import { useI18n } from 'vue-i18n';
import { useSettingsStore } from '../stores/settings.store';
import { useConnectionsStore } from '../stores/connections.store'; // +++ Import connections store +++
// @ts-ignore - guacamole-common-js 缺少官方类型定义
import Guacamole from 'guacamole-common-js';
import apiClient from '../utils/apiClient';
@@ -36,69 +37,100 @@ const MIN_MODAL_HEIGHT = 768;
// Dynamically construct WebSocket URL based on environment
let backendBaseUrl: string;
const LOCAL_BACKEND_URL = 'ws://localhost:3001'
const LOCAL_BACKEND_URL = 'ws://localhost:3001'; // For RDP proxy via main backend
// Determine WebSocket URL based on hostname
// Determine WebSocket URL based on hostname for RDP
if (window.location.hostname === 'localhost') {
backendBaseUrl = LOCAL_BACKEND_URL;
console.log(`[RDP 模态框] 使用 localhost WebSocket 基础 URL: ${backendBaseUrl}`);
console.log(`[RemoteDesktopModal] Using localhost RDP WebSocket base URL: ${backendBaseUrl}`);
} else {
// 备选方案: 根据当前 window.location 为生产环境或其他环境构建 URL
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsHostAndPort = window.location.host;
backendBaseUrl = `${wsProtocol}//${wsHostAndPort}/ws`;
console.log(`[RDP 模态框] 使用生产环境 WebSocket 基础 URL (来自 window.location): ${backendBaseUrl}`);
backendBaseUrl = `${wsProtocol}//${wsHostAndPort}/ws`; // Assuming RDP proxy is at /ws path
console.log(`[RemoteDesktopModal] Using production RDP WebSocket base URL (from window.location): ${backendBaseUrl}`);
}
const connectRdp = async () => {
// NEW: VNC WebSocket URL determination
let vncWsBaseUrl: string;
const VNC_WS_PORT_FROM_ENV = import.meta.env.VITE_VNC_WS_PORT || '8082'; // Get from env or default
if (window.location.hostname === 'localhost') {
vncWsBaseUrl = `ws://localhost:${VNC_WS_PORT_FROM_ENV}`;
console.log(`[RemoteDesktopModal] Using localhost VNC WebSocket base URL: ${vncWsBaseUrl}`);
} else {
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
// Assuming VNC proxy runs on the same host but different port (or path if configured)
vncWsBaseUrl = `${wsProtocol}//${window.location.hostname}:${VNC_WS_PORT_FROM_ENV}`;
console.log(`[RemoteDesktopModal] Using production VNC WebSocket base URL: ${vncWsBaseUrl}`);
}
const handleConnection = async () => {
if (!props.connection || !rdpDisplayRef.value) {
statusMessage.value = t('remoteDesktopModal.errors.missingInfo');
connectionStatus.value = 'error';
return;
}
// Clear previous display and disconnect
while (rdpDisplayRef.value.firstChild) {
rdpDisplayRef.value.removeChild(rdpDisplayRef.value.firstChild);
}
disconnectRdp();
disconnectGuacamole(); // Renamed from disconnectRdp
connectionStatus.value = 'connecting';
statusMessage.value = t('remoteDesktopModal.status.fetchingToken');
try {
const apiUrl = `connections/${props.connection.id}/rdp-session`;
let token: string | null = null;
let tunnelUrl: string = '';
const connectionsStore = useConnectionsStore();
const response = await apiClient.post<{ token: string }>(apiUrl);
if (props.connection.type === 'RDP') {
const apiUrl = `connections/${props.connection.id}/rdp-session`;
const response = await apiClient.post<{ token: string }>(apiUrl);
token = response.data?.token;
if (!token) {
throw new Error('RDP Token not found in API response');
}
statusMessage.value = t('remoteDesktopModal.status.connectingWs');
const token = response.data?.token;
if (!token) {
throw new Error('Token not found in API response');
}
statusMessage.value = t('remoteDesktopModal.status.connectingWs');
await nextTick();
let widthToSend = 800;
let heightToSend = 600;
const dpiToSend = 96;
// DOM 更新后获取 RDP 容器尺寸
await nextTick();
let widthToSend = 800; // 默认/备用宽度
let heightToSend = 600; // 默认/备用高度
const dpiToSend = 96;
if (rdpContainerRef.value) {
// 使用 clientWidth/clientHeight,因为它们代表可用于内容的内部尺寸
if (rdpContainerRef.value) {
widthToSend = rdpContainerRef.value.clientWidth;
heightToSend = rdpContainerRef.value.clientHeight - 1; // 根据反馈减去 1
// 确保最小尺寸,必要时根据后端要求进行调整
heightToSend = rdpContainerRef.value.clientHeight - 1;
widthToSend = Math.max(100, widthToSend);
heightToSend = Math.max(100, heightToSend);
console.log(`计算出的 RDP 尺寸: ${widthToSend}x${heightToSend}`);
}
tunnelUrl = `${backendBaseUrl}/rdp-proxy?token=${encodeURIComponent(token)}&width=${widthToSend}&height=${heightToSend}&dpi=${dpiToSend}`;
console.log(`[RemoteDesktopModal] Connecting to RDP tunnel: ${tunnelUrl}`);
} else if (props.connection.type === 'VNC') {
token = await connectionsStore.getVncSessionToken(props.connection.id);
if (!token) {
throw new Error('VNC Token not found from store action');
}
statusMessage.value = t('remoteDesktopModal.status.connectingWs'); // Generic message
tunnelUrl = `${vncWsBaseUrl}?token=${encodeURIComponent(token)}`;
// Optional: Add width/height if VNC proxy needs them, though Guacamole usually handles this post-connection.
// await nextTick();
// let widthToSend = 800;
// let heightToSend = 600;
// if (rdpContainerRef.value) {
// widthToSend = rdpContainerRef.value.clientWidth;
// heightToSend = rdpContainerRef.value.clientHeight - 1;
// widthToSend = Math.max(100, widthToSend);
// heightToSend = Math.max(100, heightToSend);
// tunnelUrl += `&width=${widthToSend}&height=${heightToSend}`;
// }
console.log(`[RemoteDesktopModal] Connecting to VNC tunnel: ${tunnelUrl}`);
} else {
console.warn("RDP 容器引用不可用,无法获取尺寸。使用默认值。");
// 考虑设置错误状态或通知用户
throw new Error(`Unsupported connection type: ${props.connection.type}`);
}
// 使用确定的基础 URL 构建后端代理端点的 URL
const tunnelUrl = `${backendBaseUrl}/rdp-proxy?token=${encodeURIComponent(token)}&width=${widthToSend}&height=${heightToSend}&dpi=${dpiToSend}`;
console.log(`[RDP 模态框] 连接到隧道: ${tunnelUrl}`); // 记录最终 URL
// @ts-ignore
const tunnel = new Guacamole.WebSocketTunnel(tunnelUrl);
@@ -107,82 +139,77 @@ const connectRdp = async () => {
const errorCode = status.code || 'N/A';
statusMessage.value = `${t('remoteDesktopModal.errors.tunnelError')} (${errorCode}): ${errorMessage}`;
connectionStatus.value = 'error';
disconnectRdp();
disconnectGuacamole();
};
// @ts-ignore
guacClient.value = new Guacamole.Client(tunnel);
// 添加此行以启用 keep-alive (每 3 秒发送 NOP)
guacClient.value.keepAliveFrequency = 3000; // 毫秒
guacClient.value.keepAliveFrequency = 3000;
rdpDisplayRef.value.appendChild(guacClient.value.getDisplay().getElement());
guacClient.value.onstatechange = (state: number) => {
let currentStatus = '';
let i18nKeyPart = 'unknownState';
switch (state) {
case 0:
statusMessage.value = t('remoteDesktopModal.status.idle');
connectionStatus.value = 'disconnected';
case 0: // IDLE
i18nKeyPart = 'idle';
currentStatus = 'disconnected';
break;
case 1:
statusMessage.value = t('remoteDesktopModal.status.connectingRdp');
connectionStatus.value = 'connecting';
case 1: // CONNECTING
i18nKeyPart = props.connection?.type === 'VNC' ? 'connectingVnc' : 'connectingRdp';
currentStatus = 'connecting';
break;
case 2:
statusMessage.value = t('remoteDesktopModal.status.waiting');
connectionStatus.value = 'connecting';
case 2: // WAITING
i18nKeyPart = 'waiting';
currentStatus = 'connecting';
break;
case 3:
statusMessage.value = t('remoteDesktopModal.status.connected');
connectionStatus.value = 'connected';
case 3: // CONNECTED
i18nKeyPart = 'connected';
currentStatus = 'connected';
setupInputListeners();
// 连接成功后,尝试将焦点设置到 RDP 显示区域
nextTick(() => {
const displayEl = guacClient.value?.getDisplay()?.getElement();
if (displayEl && typeof displayEl.focus === 'function') {
displayEl.focus();
console.log('[RDP Modal] Focused RDP display after connection.');
} else {
console.warn('[RDP Modal] Could not focus RDP display after connection.');
}
});
setTimeout(() => {
setTimeout(() => { // z-index fix for canvas
nextTick(() => {
if (rdpDisplayRef.value && guacClient.value) {
const canvases = rdpDisplayRef.value.querySelectorAll('canvas');
canvases.forEach((canvas) => {
canvas.style.zIndex = '999';
});
canvases.forEach((canvas) => { canvas.style.zIndex = '999'; });
}
});
}, 100);
break;
case 4:
statusMessage.value = t('remoteDesktopModal.status.disconnecting');
connectionStatus.value = 'disconnected';
case 4: // DISCONNECTING
i18nKeyPart = 'disconnecting';
currentStatus = 'disconnected'; // Or 'disconnecting'
break;
case 5:
statusMessage.value = t('remoteDesktopModal.status.disconnected');
connectionStatus.value = 'disconnected';
case 5: // DISCONNECTED
i18nKeyPart = 'disconnected';
currentStatus = 'disconnected';
break;
default:
statusMessage.value = `${t('remoteDesktopModal.status.unknownState')}: ${state}`;
}
statusMessage.value = t(`remoteDesktopModal.status.${i18nKeyPart}`, { state });
if (currentStatus) connectionStatus.value = currentStatus as 'disconnected' | 'connecting' | 'connected' | 'error';
};
guacClient.value.onerror = (status: any) => {
const errorMessage = status.message || 'Unknown client error';
statusMessage.value = `${t('remoteDesktopModal.errors.clientError')}: ${errorMessage}`;
connectionStatus.value = 'error';
disconnectRdp();
disconnectGuacamole();
};
guacClient.value.connect(''); // 保留 '' 的更改
guacClient.value.connect('');
} catch (error: any) {
statusMessage.value = `${t('remoteDesktopModal.errors.connectionFailed')}: ${error.response?.data?.message || error.message || String(error)}`;
connectionStatus.value = 'error';
disconnectRdp();
disconnectGuacamole();
}
};
@@ -315,7 +342,7 @@ const enableRdpKeyboard = () => {
});
};
const disconnectRdp = () => {
const disconnectGuacamole = () => {
removeInputListeners();
isKeyboardDisabledForInput.value = false; // 确保状态重置
if (guacClient.value) {
@@ -335,7 +362,7 @@ const disconnectRdp = () => {
const closeModal = () => {
disconnectRdp();
disconnectGuacamole();
emit('close');
};
@@ -411,7 +438,7 @@ onMounted(() => {
if (props.connection) {
nextTick(async () => {
await connectRdp(); // 使用初始尺寸连接
await handleConnection(); // 使用初始尺寸连接
// 不再需要设置 observer
});
} else {
@@ -421,17 +448,17 @@ onMounted(() => {
});
onUnmounted(() => {
disconnectRdp(); // 这里已经调用了 removeInputListeners
disconnectGuacamole(); // 这里已经调用了 removeInputListeners
});
watch(() => props.connection, (newConnection, oldConnection) => {
if (newConnection && newConnection.id !== oldConnection?.id) {
nextTick(async () => {
await connectRdp(); // 使用初始尺寸连接
await handleConnection(); // 使用初始尺寸连接
// 不再需要设置 observer
});
} else if (!newConnection) {
disconnectRdp();
disconnectGuacamole();
statusMessage.value = t('remoteDesktopModal.errors.noConnection');
connectionStatus.value = 'error';
}
@@ -491,7 +518,7 @@ const computedModalStyle = computed(() => {
<i v-else class="fas fa-exclamation-triangle fa-2x mb-3 text-red-400"></i>
<p class="text-sm">{{ statusMessage }}</p>
<button v-if="connectionStatus === 'error'"
@click="() => connectRdp()"
@click="() => handleConnection()"
class="mt-4 px-3 py-1 bg-primary text-white rounded text-xs hover:bg-primary-dark">
{{ t('common.retry') }}
</button>
@@ -523,12 +550,12 @@ const computedModalStyle = computed(() => {
/>
<!-- 添加重新连接按钮 -->
<button
@click="connectRdp"
:disabled="connectionStatus === 'connecting'"
class="px-4 py-2 bg-button text-button-text rounded-md shadow-sm hover:bg-button-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed transition duration-150 ease-in-out"
:title="t('remoteDesktopModal.reconnectTooltip')"
@click="handleConnection"
:disabled="connectionStatus === 'connecting'"
class="px-4 py-2 bg-button text-button-text rounded-md shadow-sm hover:bg-button-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed transition duration-150 ease-in-out"
:title="t('remoteDesktopModal.reconnectTooltip')"
>
{{ t('common.reconnect') }}
{{ t('common.reconnect') }}
</button>
</div>
</div>
+4
View File
@@ -141,6 +141,7 @@
"password": "Password:",
"privateKey": "Private Key:",
"passphrase": "Passphrase:",
"vncPassword": "VNC Password",
"optional": "Optional",
"confirm": "Confirm Add",
"adding": "Adding...",
@@ -150,6 +151,7 @@
"errorPrivateKeyRequired": "Private key is required for key authentication.",
"errorPasswordRequiredOnSwitch": "Password is required when switching to password authentication.",
"errorPrivateKeyRequiredOnSwitch": "Private key is required when switching to key authentication.",
"errorVncPasswordRequired": "VNC password is required.",
"errorPort": "Port must be between 1 and 65535.",
"errorAdd": "Failed to add connection: {error}",
"titleEdit": "Edit Connection",
@@ -165,6 +167,7 @@
"connectionType": "Connection Type:",
"typeSsh": "SSH",
"typeRdp": "RDP",
"typeVnc": "VNC",
"sectionBasic": "Basic Information",
"sectionAuth": "Authentication",
"sectionAdvanced": "Advanced Options",
@@ -897,6 +900,7 @@
"connectingWs": "Connecting WebSocket...",
"idle": "Idle",
"connectingRdp": "Connecting Remote Desktop...",
"connectingVnc": "Connecting VNC...",
"waiting": "Waiting for server response...",
"connected": "Connected",
"disconnecting": "Disconnecting...",
+5 -1
View File
@@ -141,6 +141,7 @@
"password": "密码:",
"privateKey": "私钥:",
"passphrase": "私钥密码:",
"vncPassword": "VNC 密码:",
"optional": "可选",
"confirm": "确认添加",
"adding": "正在添加...",
@@ -150,6 +151,7 @@
"errorPrivateKeyRequired": "使用密钥认证时,私钥为必填项。",
"errorPasswordRequiredOnSwitch": "切换到密码认证时,密码为必填项。",
"errorPrivateKeyRequiredOnSwitch": "切换到密钥认证时,私钥为必填项。",
"errorVncPasswordRequired": "VNC 密码是必填项。",
"errorPort": "端口号必须在 1 到 65535 之间。",
"errorAdd": "添加连接失败: {error}",
"titleEdit": "编辑连接",
@@ -165,6 +167,7 @@
"connectionType": "连接类型",
"typeSsh": "SSH",
"typeRdp": "RDP",
"typeVnc": "VNC",
"sectionBasic": "基本信息",
"sectionAuth": "认证信息",
"sectionAdvanced": "高级选项",
@@ -900,8 +903,9 @@
"connectingWs": "正在连接 WebSocket...",
"idle": "空闲",
"connectingRdp": "正在连接远程桌面...",
"connectingVnc": "正在连接 VNC...",
"waiting": "等待服务器响应...",
"connecting": "连接中...",
"connecting": "连接中...",
"error": "错误",
"connected": "已连接",
"disconnecting": "正在断开连接...",
@@ -5,7 +5,7 @@ import apiClient from '../utils/apiClient'; // 使用统一的 apiClient
export interface ConnectionInfo {
id: number;
name: string;
type: 'SSH' | 'RDP'; // Use uppercase to match backend data
type: 'SSH' | 'RDP' | 'VNC'; // Use uppercase to match backend data
host: string;
port: number;
username: string;
@@ -17,6 +17,7 @@ export interface ConnectionInfo {
updated_at: number;
last_connected_at: number | null;
notes?: string | null; // 新增备注字段
vncPassword?: string; // VNC specific password
}
// 定义 Store State 的接口
@@ -87,14 +88,15 @@ export const useConnectionsStore = defineStore('connections', {
// 更新参数类型以接受新的认证字段
async addConnection(newConnectionData: {
name: string;
type: 'SSH' | 'RDP'; // Use uppercase
type: 'SSH' | 'RDP' | 'VNC'; // Use uppercase
host: string;
port: number;
username: string;
auth_method: 'password' | 'key';
password?: string;
private_key?: string;
passphrase?: string;
auth_method: 'password' | 'key'; // SSH specific
password?: string; // SSH password or general password
private_key?: string; // SSH specific
passphrase?: string; // SSH specific
vncPassword?: string; // VNC specific password
proxy_id?: number | null;
tag_ids?: number[]; // 新增:允许传入 tag_ids
}) {
@@ -122,8 +124,8 @@ export const useConnectionsStore = defineStore('connections', {
// 更新连接 Action
// 更新参数类型以包含 proxy_id 和 tag_ids
// Update parameter type to include 'type'
async updateConnection(connectionId: number, updatedData: Partial<Omit<ConnectionInfo, 'id' | 'created_at' | 'updated_at' | 'last_connected_at'> & { type?: 'SSH' | 'RDP'; password?: string; private_key?: string; passphrase?: string; proxy_id?: number | null; tag_ids?: number[] }>) {
// Update parameter type to include 'type' and VNC fields
async updateConnection(connectionId: number, updatedData: Partial<Omit<ConnectionInfo, 'id' | 'created_at' | 'updated_at' | 'last_connected_at'> & { type?: 'SSH' | 'RDP' | 'VNC'; password?: string; private_key?: string; passphrase?: string; vncPassword?: string; proxy_id?: number | null; tag_ids?: number[] }>) {
this.isLoading = true;
this.error = null;
try {
@@ -282,5 +284,26 @@ export const useConnectionsStore = defineStore('connections', {
this.isLoading = false;
}
},
// +++ 新增:获取 VNC 会话令牌 +++
async getVncSessionToken(connectionId: number): Promise<string | null> {
// this.isLoading = true; // 考虑是否需要独立的加载状态,或者由调用方处理
// this.error = null;
try {
// 调用后端 API GET /connections/:id/vnc-session
const response = await apiClient.get<{ token: string }>(`/connections/${connectionId}/vnc-session`);
return response.data.token;
} catch (err: any) {
console.error(`获取 VNC 会话令牌失败 (连接 ID: ${connectionId}):`, err);
// this.error = err.response?.data?.message || err.message || '获取 VNC 会话令牌时发生未知错误。';
if (err.response?.status === 401) {
console.warn('未授权,需要登录才能获取 VNC 会话令牌。');
}
// 对于这种一次性获取数据的操作,错误通常由调用方处理并显示给用户
throw err; // 重新抛出错误,让调用方处理
} finally {
// this.isLoading = false;
}
},
},
});
@@ -320,7 +320,7 @@ const getTagNames = (tagIds: number[] | undefined): string[] => {
<li v-for="conn in filteredAndSortedConnections" :key="conn.id" class="flex items-center justify-between p-3 bg-header/50 border border-border/50 rounded transition duration-150 ease-in-out">
<div class="flex-grow mr-4 overflow-hidden">
<span class="font-medium block truncate flex items-center" :title="conn.name || ''">
<i :class="['fas', conn.type === 'RDP' ? 'fa-desktop' : 'fa-server', 'mr-2 w-4 text-center text-text-secondary']"></i>
<i :class="['fas', conn.type === 'RDP' || conn.type === 'VNC' ? 'fa-desktop' : 'fa-server', 'mr-2 w-4 text-center text-text-secondary']"></i>
<span>{{ conn.name || t('connections.unnamed') }}</span>
</span>
<span class="text-sm text-text-secondary block truncate" :title="`${conn.username}@${conn.host}:${conn.port}`">