feat(scripts): 添加脚本配置功能

This commit is contained in:
2025-08-26 20:08:43 +08:00
parent 183e35ac97
commit fdb724ae8b
4 changed files with 453 additions and 9 deletions

View File

@@ -2,7 +2,7 @@
<div class="scripts-grid">
<a-row :gutter="[24, 24]">
<a-col
v-for="script in scripts"
v-for="script in props.scripts"
:key="script.id"
:xs="24"
:sm="24"
@@ -33,7 +33,7 @@
</div>
<div class="header-actions">
<a-button
v-if="script.type === 'MAA'"
v-if="script.type === 'MAA' && !props.activeConnections.has(script.id)"
type="primary"
ghost
size="middle"
@@ -44,6 +44,18 @@
</template>
设置MAA全局配置
</a-button>
<a-button
v-if="script.type === 'MAA' && props.activeConnections.has(script.id)"
type="primary"
danger
size="middle"
@click="handleDisconnectMAA(script)"
>
<template #icon>
<StopOutlined />
</template>
断开配置连接
</a-button>
<a-button type="default" size="middle" @click="handleEdit(script)">
<template #icon>
<EditOutlined />
@@ -276,12 +288,14 @@ import {
EditOutlined,
PlusOutlined,
SettingOutlined,
StopOutlined,
UserAddOutlined,
UserOutlined,
} from '@ant-design/icons-vue'
interface Props {
scripts: Script[]
activeConnections: Map<string, string>
}
interface Emits {
@@ -297,6 +311,8 @@ interface Emits {
(e: 'maaConfig', script: Script): void
(e: 'disconnectMaa', script: Script): void
(e: 'toggleUserStatus', user: User): void
}
@@ -308,7 +324,7 @@ const ANNIHILATION_MAP: Record<string, string> = {
Close: '关闭',
}
defineProps<Props>()
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const handleEdit = (script: Script) => {
@@ -335,6 +351,10 @@ const handleMAAConfig = (script: Script) => {
emit('maaConfig', script)
}
const handleDisconnectMAA = (script: Script) => {
emit('disconnectMaa', script)
}
const handleToggleUserStatus = (user: User) => {
emit('toggleUserStatus', user)
}

View File

@@ -0,0 +1,223 @@
import { ref, reactive } from 'vue'
import { message, notification } from 'ant-design-vue'
import { Service } from '@/api/services/Service'
// WebSocket连接状态
export type WebSocketStatus = '连接中' | '已连接' | '已断开' | '连接错误'
// WebSocket消息类型
export interface WebSocketMessage {
type: 'Update' | 'Message' | 'Info' | 'Signal'
data?: any
message?: string
messageId?: string
}
// WebSocket连接配置
export interface WebSocketConfig {
taskId: string
mode: '设置脚本' | '自动代理' | '人工排查'
onMessage?: (data: any) => void
onStatusChange?: (status: WebSocketStatus) => void
onError?: (error: string) => void
showNotifications?: boolean
}
export function useWebSocket() {
const connections = ref<Map<string, WebSocket>>(new Map())
const statuses = ref<Map<string, WebSocketStatus>>(new Map())
// 获取WebSocket地址并建立连接
const connect = async (config: WebSocketConfig): Promise<string | null> => {
try {
// 调用API获取WebSocket连接ID
const response = await Service.addTaskApiDispatchStartPost({
taskId: config.taskId,
mode: config.mode as any,
})
if (response.code !== 200) {
const errorMsg = response.message || '获取WebSocket地址失败'
if (config.onError) {
config.onError(errorMsg)
} else {
message.error(errorMsg)
}
return null
}
const websocketId = response.websocketId
const wsUrl = `ws://localhost:8000/api/dispatch/ws/${websocketId}`
// 建立WebSocket连接
const ws = new WebSocket(wsUrl)
connections.value.set(websocketId, ws)
statuses.value.set(websocketId, '连接中')
// 通知状态变化
if (config.onStatusChange) {
config.onStatusChange('连接中')
}
ws.onopen = () => {
statuses.value.set(websocketId, '已连接')
if (config.onStatusChange) {
config.onStatusChange('已连接')
}
if (config.showNotifications !== false) {
message.success('已连接到服务器')
}
}
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data)
handleMessage(data, config)
} catch (error) {
console.error('解析WebSocket消息失败:', error)
const errorMsg = `收到无效消息: ${event.data}`
if (config.onError) {
config.onError(errorMsg)
}
}
}
ws.onclose = () => {
statuses.value.set(websocketId, '已断开')
connections.value.delete(websocketId)
if (config.onStatusChange) {
config.onStatusChange('已断开')
}
if (config.showNotifications !== false) {
message.warning('与服务器连接已断开')
}
}
ws.onerror = (error) => {
statuses.value.set(websocketId, '连接错误')
const errorMsg = '连接发生错误'
if (config.onError) {
config.onError(errorMsg)
} else if (config.showNotifications !== false) {
message.error(errorMsg)
}
console.error('WebSocket错误:', error)
}
return websocketId
} catch (error) {
const errorMsg = error instanceof Error ? error.message : '连接失败'
if (config.onError) {
config.onError(errorMsg)
} else {
message.error(errorMsg)
}
return null
}
}
// 处理WebSocket消息
const handleMessage = (data: WebSocketMessage, config: WebSocketConfig) => {
// 调用自定义消息处理器
if (config.onMessage) {
config.onMessage(data)
}
// 默认消息处理
switch (data.type) {
case 'Info':
// 通知信息
let level = 'info'
let content = '未知通知'
// 检查数据中是否有 Error 字段
if (data.data?.Error) {
level = 'error'
content = data.data.Error
} else {
content = data.data?.val || data.data?.message || data.message || '未知通知'
}
// 显示系统通知(仅在启用通知时)
if (config.showNotifications !== false) {
if (level === 'error') {
notification.error({ message: '任务错误', description: content })
} else if (level === 'warning') {
notification.warning({ message: '任务警告', description: content })
} else if (level === 'success') {
notification.success({ message: '任务成功', description: content })
} else {
notification.info({ message: '任务信息', description: content })
}
}
break
case 'Signal':
// 状态信号
if (data.data?.Accomplish !== undefined) {
const isSuccess = data.data.Accomplish
const statusMsg = isSuccess ? '任务已完成' : '任务已失败'
if (config.showNotifications !== false) {
if (isSuccess) {
notification.success({ message: '任务完成', description: statusMsg })
} else {
notification.error({ message: '任务失败', description: statusMsg })
}
}
}
break
}
}
// 断开连接
const disconnect = (websocketId: string) => {
const ws = connections.value.get(websocketId)
if (ws) {
ws.close()
connections.value.delete(websocketId)
statuses.value.delete(websocketId)
}
}
// 断开所有连接
const disconnectAll = () => {
connections.value.forEach((ws) => {
ws.close()
})
connections.value.clear()
statuses.value.clear()
}
// 发送消息
const sendMessage = (websocketId: string, message: any) => {
const ws = connections.value.get(websocketId)
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(message))
return true
}
return false
}
// 获取连接状态
const getStatus = (websocketId: string): WebSocketStatus | undefined => {
return statuses.value.get(websocketId)
}
// 检查连接是否存在
const isConnected = (websocketId: string): boolean => {
const ws = connections.value.get(websocketId)
return ws?.readyState === WebSocket.OPEN
}
return {
connections: connections.value,
statuses: statuses.value,
connect,
disconnect,
disconnectAll,
sendMessage,
getStatus,
isConnected,
}
}

View File

@@ -22,12 +22,14 @@
<ScriptTable
:scripts="scripts"
:active-connections="activeConnections"
@edit="handleEditScript"
@delete="handleDeleteScript"
@add-user="handleAddUser"
@edit-user="handleEditUser"
@delete-user="handleDeleteUser"
@maa-config="handleMAAConfig"
@disconnect-maa="handleDisconnectMAA"
@toggle-user-status="handleToggleUserStatus"
/>
@@ -74,7 +76,7 @@
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { onMounted, ref, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue'
@@ -82,20 +84,30 @@ import ScriptTable from '@/components/ScriptTable.vue'
import type { Script, ScriptType, User } from '@/types/script'
import { useScriptApi } from '@/composables/useScriptApi'
import { useUserApi } from '@/composables/useUserApi'
import { useWebSocket } from '@/composables/useWebSocket'
const router = useRouter()
const { addScript, deleteScript, getScriptsWithUsers, loading } = useScriptApi()
const { addUser, updateUser, deleteUser, loading: userLoading } = useUserApi()
const { connect, disconnect, disconnectAll } = useWebSocket()
const scripts = ref<Script[]>([])
const typeSelectVisible = ref(false)
const selectedType = ref<ScriptType>('MAA')
const addLoading = ref(false)
// WebSocket连接管理
const activeConnections = ref<Map<string, string>>(new Map()) // scriptId -> websocketId
onMounted(() => {
loadScripts()
})
onUnmounted(() => {
// 清理所有WebSocket连接
disconnectAll()
})
const loadScripts = async () => {
try {
const scriptDetails = await getScriptsWithUsers()
@@ -199,10 +211,62 @@ const handleRefresh = () => {
message.success('刷新成功')
}
const handleMAAConfig = (script: Script) => {
// TODO: 实现MAA全局配置功能
console.log('设置MAA全局配置:', script)
message.info('MAA全局配置功能待实现')
const handleMAAConfig = async (script: Script) => {
try {
// 检查是否已有连接
const existingWebsocketId = activeConnections.value.get(script.id)
if (existingWebsocketId) {
message.warning('该脚本已在配置中,请先断开连接')
return
}
// 建立WebSocket连接进行MAA配置
const websocketId = await connect({
taskId: script.id,
mode: '设置脚本',
showNotifications: true,
onStatusChange: (status) => {
console.log(`脚本 ${script.name} 连接状态: ${status}`)
},
onMessage: (data) => {
console.log(`脚本 ${script.name} 收到消息:`, data)
// 这里可以根据需要处理特定的消息
},
onError: (error) => {
console.error(`脚本 ${script.name} 连接错误:`, error)
message.error(`MAA配置连接失败: ${error}`)
// 清理连接记录
activeConnections.value.delete(script.id)
}
})
if (websocketId) {
// 记录连接
activeConnections.value.set(script.id, websocketId)
message.success(`已开始配置 ${script.name}`)
// 可选设置自动断开连接的定时器比如30分钟后
setTimeout(() => {
if (activeConnections.value.has(script.id)) {
disconnect(websocketId)
activeConnections.value.delete(script.id)
message.info(`${script.name} 配置会话已超时断开`)
}
}, 30 * 60 * 1000) // 30分钟
}
} catch (error) {
console.error('MAA配置失败:', error)
message.error('MAA配置失败')
}
}
const handleDisconnectMAA = (script: Script) => {
const websocketId = activeConnections.value.get(script.id)
if (websocketId) {
disconnect(websocketId)
activeConnections.value.delete(script.id)
message.success(`已断开 ${script.name} 的配置连接`)
}
}
const handleToggleUserStatus = async (user: User) => {

View File

@@ -17,6 +17,32 @@
</div>
<a-space size="middle">
<a-button
v-if="scriptType === 'MAA'"
type="primary"
ghost
size="large"
@click="handleMAAConfig"
:loading="maaConfigLoading"
>
<template #icon>
<SettingOutlined />
</template>
MAA配置
</a-button>
<a-button
v-if="scriptType === 'General'"
type="primary"
ghost
size="large"
@click="handleGeneralConfig"
:loading="generalConfigLoading"
>
<template #icon>
<SettingOutlined />
</template>
通用配置
</a-button>
<a-button size="large" @click="handleCancel" class="cancel-button">
<template #icon>
<ArrowLeftOutlined />
@@ -926,15 +952,17 @@
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { ArrowLeftOutlined, QuestionCircleOutlined, SaveOutlined } from '@ant-design/icons-vue'
import { ArrowLeftOutlined, QuestionCircleOutlined, SaveOutlined, SettingOutlined } from '@ant-design/icons-vue'
import type { FormInstance, Rule } from 'ant-design-vue/es/form'
import { useUserApi } from '@/composables/useUserApi'
import { useScriptApi } from '@/composables/useScriptApi'
import { useWebSocket } from '@/composables/useWebSocket'
const router = useRouter()
const route = useRoute()
const { addUser, updateUser, getUsers, loading: userLoading } = useUserApi()
const { getScript } = useScriptApi()
const { connect, disconnect } = useWebSocket()
const formRef = ref<FormInstance>()
const loading = computed(() => userLoading.value)
@@ -948,6 +976,14 @@ const isEdit = computed(() => !!userId)
const scriptName = ref('')
const scriptType = ref<'MAA' | 'General'>('MAA')
// MAA配置相关
const maaConfigLoading = ref(false)
const maaWebsocketId = ref<string | null>(null)
// 通用配置相关
const generalConfigLoading = ref(false)
const generalWebsocketId = ref<string | null>(null)
// 服务器选项
const serverOptions = [
{ label: '官服', value: 'Official' },
@@ -1212,7 +1248,108 @@ const handleSubmit = async () => {
}
}
const handleMAAConfig = async () => {
if (!isEdit.value) {
message.warning('请先保存用户后再进行MAA配置')
return
}
try {
maaConfigLoading.value = true
// 如果已有连接,先断开
if (maaWebsocketId.value) {
disconnect(maaWebsocketId.value)
maaWebsocketId.value = null
}
// 建立WebSocket连接进行MAA配置
const websocketId = await connect({
taskId: userId, // 使用用户ID进行配置
mode: '设置脚本',
showNotifications: true,
onStatusChange: (status) => {
console.log(`用户 ${formData.userName} MAA配置状态: ${status}`)
},
onMessage: (data) => {
console.log(`用户 ${formData.userName} MAA配置消息:`, data)
// 这里可以根据需要处理特定的消息
},
onError: (error) => {
console.error(`用户 ${formData.userName} MAA配置错误:`, error)
message.error(`MAA配置连接失败: ${error}`)
maaWebsocketId.value = null
}
})
if (websocketId) {
maaWebsocketId.value = websocketId
message.success(`已开始配置用户 ${formData.userName} 的MAA设置`)
}
} catch (error) {
console.error('MAA配置失败:', error)
message.error('MAA配置失败')
} finally {
maaConfigLoading.value = false
}
}
const handleGeneralConfig = async () => {
if (!isEdit.value) {
message.warning('请先保存用户后再进行通用配置')
return
}
try {
generalConfigLoading.value = true
// 如果已有连接,先断开
if (generalWebsocketId.value) {
disconnect(generalWebsocketId.value)
generalWebsocketId.value = null
}
// 建立WebSocket连接进行通用配置
const websocketId = await connect({
taskId: userId, // 使用用户ID进行配置
mode: '设置脚本',
showNotifications: true,
onStatusChange: (status) => {
console.log(`用户 ${formData.userName} 通用配置状态: ${status}`)
},
onMessage: (data) => {
console.log(`用户 ${formData.userName} 通用配置消息:`, data)
// 这里可以根据需要处理特定的消息
},
onError: (error) => {
console.error(`用户 ${formData.userName} 通用配置错误:`, error)
message.error(`通用配置连接失败: ${error}`)
generalWebsocketId.value = null
}
})
if (websocketId) {
generalWebsocketId.value = websocketId
message.success(`已开始配置用户 ${formData.userName} 的通用设置`)
}
} catch (error) {
console.error('通用配置失败:', error)
message.error('通用配置失败')
} finally {
generalConfigLoading.value = false
}
}
const handleCancel = () => {
// 清理WebSocket连接
if (maaWebsocketId.value) {
disconnect(maaWebsocketId.value)
maaWebsocketId.value = null
}
if (generalWebsocketId.value) {
disconnect(generalWebsocketId.value)
generalWebsocketId.value = null
}
router.push('/scripts')
}