using AmtScanner.Api.Data; using AmtScanner.Api.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace AmtScanner.Api.Controllers; [ApiController] [Route("api/[controller]")] public class RemoteDesktopController : ControllerBase { private readonly IGuacamoleService _guacamoleService; private readonly AppDbContext _context; private readonly ILogger _logger; public RemoteDesktopController( IGuacamoleService guacamoleService, AppDbContext context, ILogger logger) { _guacamoleService = guacamoleService; _context = context; _logger = logger; } /// /// 获取远程桌面连接 URL /// [HttpPost("connect/{deviceId}")] public async Task> Connect(long deviceId, [FromBody] RdpCredentials credentials) { var device = await _context.AmtDevices.FindAsync(deviceId); if (device == null) { return NotFound(new { error = "设备不存在" }); } // 获取 Guacamole Token var token = await _guacamoleService.GetAuthTokenAsync(); if (string.IsNullOrEmpty(token)) { return StatusCode(503, new { error = "无法连接到 Guacamole 服务,请确保 Guacamole 已启动" }); } // 创建或获取连接 var connectionName = $"AMT-{device.IpAddress}"; var connectionId = await _guacamoleService.CreateOrGetConnectionAsync( token, connectionName, device.IpAddress, credentials.Username, credentials.Password); if (string.IsNullOrEmpty(connectionId)) { return StatusCode(500, new { error = "创建远程连接失败" }); } // 获取连接 URL var connectionUrl = await _guacamoleService.GetConnectionUrlAsync(token, connectionId); _logger.LogInformation("Created remote desktop connection for device {Ip}, connectionId: {Id}", device.IpAddress, connectionId); return Ok(new RemoteDesktopResponse { Success = true, ConnectionUrl = connectionUrl, ConnectionId = connectionId, Token = token }); } /// /// 测试 Guacamole 连接 /// [HttpGet("test")] public async Task TestConnection() { var token = await _guacamoleService.GetAuthTokenAsync(); if (string.IsNullOrEmpty(token)) { return StatusCode(503, new { success = false, error = "无法连接到 Guacamole 服务" }); } return Ok(new { success = true, message = "Guacamole 服务连接正常" }); } } public class RdpCredentials { public string Username { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; } public class RemoteDesktopResponse { public bool Success { get; set; } public string? ConnectionUrl { get; set; } public string? ConnectionId { get; set; } public string? Token { get; set; } public string? Error { get; set; } }