using ClassNotify.Server.Hubs; using ClassNotify.Server.Services; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; namespace ClassNotify.Server.Controllers; public class SendDeviceCommandRequest { public string DeviceId { get; set; } = string.Empty; public string CommandType { get; set; } = string.Empty; public string? Parameters { get; set; } } [ApiController] [Route("api/device-command")] [Authorize] public class DeviceCommandController : ControllerBase { private readonly ISecurityService _securityService; private readonly IHubContext _deviceHub; private readonly ILogger _logger; public DeviceCommandController( ISecurityService securityService, IHubContext deviceHub, ILogger logger) { _securityService = securityService; _deviceHub = deviceHub; _logger = logger; } /// /// 下发受控远程运维命令 (SelfCheck, RestartClient, Reconnect, RefreshConfig) /// [HttpPost("send")] [Authorize(Roles = "SuperAdmin,SchoolAdmin,Teacher,TenantOwner")] public async Task SendCommand([FromBody] SendDeviceCommandRequest req) { if (req == null || string.IsNullOrWhiteSpace(req.DeviceId) || string.IsNullOrWhiteSpace(req.CommandType)) { return BadRequest(new { success = false, message = "设备编号与指令类型不可为空" }); } var isSuperAdmin = User.IsInRole("SuperAdmin"); var tenantId = isSuperAdmin ? null : User.FindFirst("tenant_id")?.Value; var callerUser = User.Identity?.Name ?? User.FindFirst("name")?.Value ?? "User"; try { var cmdDto = await _securityService.CreateDeviceCommandAsync( tenantId, req.DeviceId, req.CommandType, req.Parameters, callerUser); var connId = _securityService.GetDeviceConnectionId(req.DeviceId); if (!string.IsNullOrEmpty(connId)) { await _deviceHub.Clients.Client(connId).ReceiveRemoteCommand(cmdDto); await _securityService.MarkCommandDispatchedAsync(cmdDto.CommandId); cmdDto.Status = DeviceCommandStatuses.Dispatched; _logger.LogInformation("Dispatched command {CommandId} ({Type}) to device {DeviceId} via SignalR {ConnId}", cmdDto.CommandId, cmdDto.CommandType, req.DeviceId, connId); } else { _logger.LogInformation("Device {DeviceId} is offline. Command {CommandId} queued as Pending until {ExpiresAt:u}", req.DeviceId, cmdDto.CommandId, cmdDto.ExpiresAt); } return Ok(new { success = true, command = cmdDto, isDispatched = !string.IsNullOrEmpty(connId), message = string.IsNullOrEmpty(connId) ? $"设备当前离线,指令已排队,将在设备上线且未过期时补发 (过期时间: {cmdDto.ExpiresAt:u})" : $"指令已通过 SignalR 实时下发至设备 (过期时间: {cmdDto.ExpiresAt:u})" }); } catch (ArgumentException ex) { return BadRequest(new { success = false, message = ex.Message }); } catch (UnauthorizedAccessException ex) { return StatusCode(StatusCodes.Status403Forbidden, new { success = false, message = ex.Message }); } catch (InvalidOperationException ex) { return NotFound(new { success = false, message = ex.Message }); } catch (Exception ex) { _logger.LogError(ex, "Unexpected error sending command to device {DeviceId}", req.DeviceId); return StatusCode(500, new { success = false, message = "下发指令内部错误" }); } } /// /// 查询单条命令当前状态与执行结果 /// [HttpGet("{commandId}")] public async Task GetCommand(string commandId) { if (string.IsNullOrWhiteSpace(commandId)) { return BadRequest(new { success = false, message = "CommandId 不可为空" }); } var isSuperAdmin = User.IsInRole("SuperAdmin"); var tenantId = isSuperAdmin ? null : User.FindFirst("tenant_id")?.Value; var cmd = await _securityService.GetDeviceCommandAsync(commandId, tenantId); if (cmd == null) { return NotFound(new { success = false, message = "命令未找到或无权访问" }); } return Ok(cmd); } /// /// 获取命令审计流水历史记录 /// [HttpGet("history")] public async Task GetHistory( [FromQuery] string? deviceId = null, [FromQuery] string? status = null, [FromQuery] int limit = 50) { var isSuperAdmin = User.IsInRole("SuperAdmin"); var tenantId = isSuperAdmin ? null : User.FindFirst("tenant_id")?.Value; var history = await _securityService.GetDeviceCommandHistoryAsync(tenantId, deviceId, status, limit); return Ok(history); } }