using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Hubs; using ClassNotify.Server.Infrastructure.Correlation; using ClassNotify.Server.Services; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Controllers; [ApiController] [Route("api/[controller]")] [EnableRateLimiting("ActivationLimiter")] public class DeviceController : ControllerBase { private readonly ISecurityService _securityService; private readonly IVisualReceiptService _visualReceiptService; private readonly IHubContext _teacherHubContext; private readonly ClassNotifyDbContext _dbContext; private readonly ICorrelationContext _correlationContext; private readonly IPairingService _pairingService; private readonly IDeviceNotificationService _deviceNotificationService; private readonly ILogger _logger; public DeviceController( ISecurityService securityService, IVisualReceiptService visualReceiptService, IHubContext teacherHubContext, ClassNotifyDbContext dbContext, ICorrelationContext correlationContext, IPairingService pairingService, IDeviceNotificationService deviceNotificationService, ILogger logger) { _securityService = securityService; _visualReceiptService = visualReceiptService; _teacherHubContext = teacherHubContext; _dbContext = dbContext; _correlationContext = correlationContext; _pairingService = pairingService; _deviceNotificationService = deviceNotificationService; _logger = logger; } /// /// 设备端健康心跳与时间同步探针接口 /// [HttpGet("ping")] [HttpGet("/api/devices/ping")] public IActionResult Ping([FromServices] IConfiguration config) { var releaseId = Environment.GetEnvironmentVariable("CLASSNOTIFY_RELEASE_ID") ?? (System.IO.File.Exists("release.txt") ? System.IO.File.ReadAllText("release.txt").Trim() : null) ?? config["Release:Id"] ?? "20260925-P25-RC0"; return Ok(new { serverUtc = DateTimeOffset.UtcNow, releaseId = releaseId, correlationId = _correlationContext.CorrelationId }); } /// /// 教室端初次安装激活接口 (通过一次性激活码换取永久硬件凭据) /// [HttpPost("activate")] public async Task Activate([FromBody] DeviceActivationRequestDto dto) { var result = await _securityService.ActivateDeviceAsync(dto); if (!result.Success) { if (result.ErrorMessage?.Contains("其他设备安装实例") == true) { return Conflict(result); } return BadRequest(result); } // GPT Turn 76 Protocol: Invalidate stale SignalR session immediately by DeviceId, InstallationId, and HardwareComponentsHash await _securityService.InvalidateDeviceSessionByEndpointAsync(result.DeviceId, dto.InstallationId, dto.HardwareComponentsHash, "Activated"); return Ok(result); } /// /// 设备端主动查询权威授权状态 (Event for realtime, GET for recovery) /// [HttpGet("license")] public async Task GetLicense() { var deviceId = Request.Headers["X-Device-Id"].FirstOrDefault(); var token = Request.Headers["X-Device-Token"].FirstOrDefault(); if (string.IsNullOrEmpty(deviceId) || string.IsNullOrEmpty(token)) { return Unauthorized(new { success = false, message = "缺少设备身份凭据" }); } var device = await _securityService.ValidateDeviceAsync(deviceId, token); if (device == null) { return Unauthorized(new { success = false, message = "设备凭据无效" }); } var status = await _securityService.GetDeviceLicenseStatusAsync(deviceId); return Ok(status); } /// /// 教室大屏/设备端直接输入激活码进行续费 /// [HttpPost("license/renew")] public async Task RenewLicense( [FromBody] RenewDeviceLicenseRequestDto dto, [FromServices] IHubContext deviceHubContext) { var deviceId = Request.Headers["X-Device-Id"].FirstOrDefault(); var token = Request.Headers["X-Device-Token"].FirstOrDefault(); if (string.IsNullOrEmpty(deviceId) || string.IsNullOrEmpty(token)) { return Unauthorized(new { success = false, message = "缺少设备身份凭据" }); } var device = await _securityService.ValidateDeviceAsync(deviceId, token); if (device == null) { return Unauthorized(new { success = false, message = "设备凭据无效" }); } var (success, message, newStatus) = await _securityService.RenewDeviceLicenseAsync( deviceId, dto.ActivationCode, dto.ExtendDays, dto.Tier, "DeviceSelfRenew", dto.Reason); if (!success) { return BadRequest(new { success = false, message }); } // Push real-time updated license status via SignalR to device group if (newStatus != null) { var devGroup = $"t:{device.TenantId}:d:{device.Id}"; await deviceHubContext.Clients.Group(devGroup).ReceiveLicenseStatus(newStatus); } return Ok(new { success = true, message, license = newStatus }); } /// /// 学校教师/管理员在线生成班级一次性设备激活码 /// [HttpPost("generate-code")] [Microsoft.AspNetCore.Authorization.Authorize(Roles = "SuperAdmin,SchoolAdmin,TenantOwner")] public async Task GenerateCode( [FromQuery] string classId, [FromQuery] int? durationDays = 7, [FromQuery] string tier = "Trial") { var tenantId = User.FindFirst("tenant_id")?.Value; if (string.IsNullOrEmpty(tenantId)) { return Unauthorized(new { success = false, message = "未发现合法的租户信息" }); } if (string.IsNullOrWhiteSpace(classId)) { return BadRequest(new { success = false, message = "班级编号不可为空" }); } var classroom = await _securityService.GetClassroomAsync(tenantId, classId); if (classroom == null) { return NotFound(new { success = false, message = $"班级 {classId} 不存在或不属于当前学校" }); } try { var username = User.Identity?.Name ?? "SchoolAdmin"; var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); var code = await _securityService.GenerateActivationCodeAsync(tenantId, classId, durationDays, tier, username, "SchoolAdmin", ip); return Ok(new { success = true, code, tenantId, classId, durationDays, tier, message = "激活码生成成功" }); } catch (Exception ex) { return BadRequest(new { success = false, message = ex.Message }); } } /// /// 教室 Windows 客户端上传单帧通知视觉回执 (JPEG 格式, 最大 512KB) /// [HttpPost("notifications/{notificationId}/visual-receipt")] [HttpPost("/api/devices/notifications/{notificationId}/visual-receipt")] [RequestSizeLimit(524288)] // 512 KiB public async Task UploadVisualReceipt(string notificationId) { var deviceId = Request.Headers["X-Device-Id"].FirstOrDefault(); var deviceToken = Request.Headers["X-Device-Token"].FirstOrDefault(); if (string.IsNullOrWhiteSpace(deviceId) || string.IsNullOrWhiteSpace(deviceToken)) { return Unauthorized(new { success = false, message = "缺少设备鉴权凭据 (X-Device-Id / X-Device-Token)" }); } if (Request.ContentType?.StartsWith("image/jpeg", StringComparison.OrdinalIgnoreCase) != true) { return StatusCode(415, new { success = false, message = "仅支持 image/jpeg 格式内容" }); } using var ms = new MemoryStream(); await Request.Body.CopyToAsync(ms); var bytes = ms.ToArray(); var result = await _visualReceiptService.SaveVisualReceiptAsync(notificationId, deviceId, deviceToken, bytes); if (!result.Success) { return StatusCode(result.StatusCode, new { success = false, message = result.Message }); } try { var device = await _securityService.ValidateDeviceAsync(deviceId, deviceToken); if (device != null && !string.IsNullOrEmpty(device.TenantId)) { var tenantTeacherGroup = $"t:{device.TenantId}:teachers"; await _teacherHubContext.Clients.Group(tenantTeacherGroup).OnVisualReceiptUploaded(new VisualReceiptUploadedEvent { NotificationId = notificationId, DeviceId = deviceId, VisualReceiptState = "Available", CapturedAt = result.CapturedAt ?? DateTimeOffset.UtcNow, ExpiresAt = result.ExpiresAt }); _logger.LogInformation("Broadcasted OnVisualReceiptUploaded for notification {NotificationId} to group {Group}", notificationId, tenantTeacherGroup); } } catch (Exception ex) { _logger.LogError(ex, "Failed to broadcast OnVisualReceiptUploaded for {NotificationId}", notificationId); } return Ok(new { success = true, receiptId = result.ReceiptId, notificationId, visualReceiptState = "Available", capturedAt = result.CapturedAt, expiresAt = result.ExpiresAt, message = result.Message }); } private static readonly System.Collections.Concurrent.ConcurrentDictionary _selfCheckLocks = new(); /// /// 终端上报结构化自检诊断报告 /// [HttpPost("self-check/{selfCheckId}/result")] [HttpPost("/api/devices/self-check/{selfCheckId}/result")] public async Task ReportSelfCheckResult(string selfCheckId, [FromBody] DeviceSelfCheckResultDto dto) { var deviceId = Request.Headers["X-Device-Id"].FirstOrDefault(); var deviceToken = Request.Headers["X-Device-Token"].FirstOrDefault(); if (string.IsNullOrWhiteSpace(deviceId) || string.IsNullOrWhiteSpace(deviceToken)) { return Unauthorized(new { success = false, message = "缺少设备鉴权凭据 (X-Device-Id / X-Device-Token)" }); } var device = await _securityService.ValidateDeviceAsync(deviceId, deviceToken); if (device == null) { return Unauthorized(new { success = false, message = "设备鉴权失败" }); } var resultJson = System.Text.Json.JsonSerializer.Serialize(dto); var now = DateTimeOffset.UtcNow; if (_dbContext.Database.IsRelational()) { var affected = await _dbContext.DeviceSelfChecks .Where(r => r.Id == selfCheckId && r.DeviceId == deviceId && r.TenantId == device.TenantId && (r.RunState == SelfCheckRunStates.PendingDispatch || r.RunState == SelfCheckRunStates.Dispatched)) .ExecuteUpdateAsync(s => s .SetProperty(r => r.RunState, SelfCheckRunStates.Completed) .SetProperty(r => r.OverallStatus, dto.OverallStatus.ToString()) .SetProperty(r => r.Status, dto.OverallStatus.ToString()) .SetProperty(r => r.CompletedAtUtc, dto.CompletedAtUtc != default ? dto.CompletedAtUtc : now) .SetProperty(r => r.ResultJson, resultJson)); if (affected == 1) { var batchId = await _dbContext.DeviceSelfChecks .Where(r => r.Id == selfCheckId) .Select(r => r.BatchId) .FirstOrDefaultAsync(); if (!string.IsNullOrEmpty(batchId)) { var activeCount = await _dbContext.DeviceSelfChecks .CountAsync(r => r.BatchId == batchId && (r.RunState == SelfCheckRunStates.PendingDispatch || r.RunState == SelfCheckRunStates.Dispatched)); if (activeCount == 0) { await _dbContext.DeviceSelfCheckBatches .Where(b => b.Id == batchId && b.Status == "Running") .ExecuteUpdateAsync(s => s .SetProperty(b => b.Status, "Completed") .SetProperty(b => b.CompletedAtUtc, now) .SetProperty(b => b.UpdatedAtUtc, now)); } } int failedChecks = dto.Checks?.Count(c => c.Status == SelfCheckStatus.Failed) ?? 0; int warningChecks = dto.Checks?.Count(c => c.Status == SelfCheckStatus.Warning) ?? 0; _logger.LogInformation("SelfCheck result recorded: BatchId={BatchId}, SelfCheckId={SelfCheckId}, DeviceId={DeviceId}, OverallStatus={OverallStatus}, FailedChecks={Failed}, WarningChecks={Warning}", batchId, selfCheckId, deviceId, dto.OverallStatus, failedChecks, warningChecks); return Ok(new { success = true, accepted = true, duplicate = false, selfCheckId, status = dto.OverallStatus.ToString() }); } } // Concurrency gate for In-Memory and fallback evaluation var sem = _selfCheckLocks.GetOrAdd(selfCheckId, _ => new SemaphoreSlim(1, 1)); await sem.WaitAsync(); try { var current = await _dbContext.DeviceSelfChecks .FirstOrDefaultAsync(r => r.Id == selfCheckId); if (current == null) { var newRun = new DeviceSelfCheckRun { Id = selfCheckId, TenantId = device.TenantId, DeviceId = deviceId, CorrelationId = string.IsNullOrEmpty(dto.CorrelationId) ? _correlationContext.CorrelationId : dto.CorrelationId, Status = dto.OverallStatus.ToString(), RunState = SelfCheckRunStates.Completed, OverallStatus = dto.OverallStatus.ToString(), RequestedAtUtc = dto.StartedAtUtc != default ? dto.StartedAtUtc : now, CompletedAtUtc = dto.CompletedAtUtc != default ? dto.CompletedAtUtc : now, ResultJson = resultJson, RequestedByUserId = "Device" }; _dbContext.DeviceSelfChecks.Add(newRun); await _dbContext.SaveChangesAsync(); return Ok(new { success = true, accepted = true, duplicate = false, selfCheckId, status = dto.OverallStatus.ToString() }); } // Cross-device/tenant defense if (current.DeviceId != deviceId || current.TenantId != device.TenantId) { return StatusCode(403, new { success = false, message = "越权拒绝:禁止提交其他终端或租户的自检记录" }); } // Already TimedOut or expired if (current.RunState == SelfCheckRunStates.TimedOut || (current.DeadlineAtUtc != default && current.DeadlineAtUtc < now)) { if (current.RunState != SelfCheckRunStates.TimedOut) { current.RunState = SelfCheckRunStates.TimedOut; current.Status = "Timeout"; current.CompletedAtUtc = now; await _dbContext.SaveChangesAsync(); } _logger.LogWarning("LateSelfCheckResultIgnored: Run {SelfCheckId} expired at {Deadline:u} and cannot be transitioned to Completed. BatchId={BatchId}, DeviceId={DeviceId}", selfCheckId, current.DeadlineAtUtc, current.BatchId, deviceId); return Ok(new { success = true, accepted = false, reason = "RunExpired", duplicate = false, selfCheckId, status = "Timeout" }); } // Already Completed (First-wins duplicate) if (current.RunState == SelfCheckRunStates.Completed) { _logger.LogInformation("SelfCheckResultIdempotent: Run {SelfCheckId} is already completed with status {OverallStatus}. Ignoring duplicate report.", selfCheckId, current.OverallStatus); return Ok(new { success = true, accepted = true, duplicate = true, selfCheckId, status = current.OverallStatus }); } // Transition to Completed current.RunState = SelfCheckRunStates.Completed; current.OverallStatus = dto.OverallStatus.ToString(); current.Status = dto.OverallStatus.ToString(); current.CompletedAtUtc = dto.CompletedAtUtc != default ? dto.CompletedAtUtc : now; current.ResultJson = resultJson; await _dbContext.SaveChangesAsync(); if (!string.IsNullOrEmpty(current.BatchId)) { var activeCount = await _dbContext.DeviceSelfChecks .CountAsync(r => r.BatchId == current.BatchId && (r.RunState == SelfCheckRunStates.PendingDispatch || r.RunState == SelfCheckRunStates.Dispatched)); if (activeCount == 0) { var batch = await _dbContext.DeviceSelfCheckBatches.FirstOrDefaultAsync(b => b.Id == current.BatchId); if (batch != null && batch.Status == "Running") { batch.Status = "Completed"; batch.CompletedAtUtc = now; batch.UpdatedAtUtc = now; await _dbContext.SaveChangesAsync(); } } } int failed = dto.Checks?.Count(c => c.Status == SelfCheckStatus.Failed) ?? 0; int warning = dto.Checks?.Count(c => c.Status == SelfCheckStatus.Warning) ?? 0; _logger.LogInformation("SelfCheck result recorded: BatchId={BatchId}, SelfCheckId={SelfCheckId}, DeviceId={DeviceId}, OverallStatus={OverallStatus}, FailedChecks={Failed}, WarningChecks={Warning}", current.BatchId, selfCheckId, deviceId, dto.OverallStatus, failed, warning); return Ok(new { success = true, accepted = true, duplicate = false, selfCheckId, status = current.OverallStatus }); } finally { sem.Release(); } } /// /// 设备端就地修改班级名称 / 大屏名称接口 /// [HttpPut("class-name")] [HttpPut("display-label")] public async Task UpdateClassName( [FromBody] UpdateClassNameRequestDto req, [FromServices] IHubContext deviceHubContext) { if (req == null || string.IsNullOrWhiteSpace(req.ClassName)) { return BadRequest(new { success = false, message = "班级名称不可为空" }); } var deviceId = Request.Headers["X-Device-Id"].FirstOrDefault(); var deviceToken = Request.Headers["X-Device-Token"].FirstOrDefault(); if (string.IsNullOrWhiteSpace(deviceId) || string.IsNullOrWhiteSpace(deviceToken)) { return Unauthorized(new { success = false, message = "缺少设备鉴权凭据 (X-Device-Id / X-Device-Token)" }); } var device = await _securityService.ValidateDeviceAsync(deviceId, deviceToken); if (device == null) { return Unauthorized(new { success = false, message = "设备鉴权失败" }); } var (success, msg, newName) = await _securityService.UpdateDeviceClassNameAsync( deviceId, req.ClassName, operatorName: $"Device:{deviceId}", operatorRole: "DeviceTerminal"); if (!success) { return BadRequest(new { success = false, message = msg }); } // Notify device group via SignalR try { await deviceHubContext.Clients.Group($"dev_{deviceId}").ClassDisplayNameChanged(newName ?? req.ClassName); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to broadcast ClassDisplayNameChanged SignalR event to device group"); } return Ok(new { success = true, message = "班级名称已更新", className = newName }); } /// /// Turn 113: 允许教室大屏硬件自身(持 X-Device-Id + X-Device-Token)主动申请开启临时配对模式 /// 生成 10 分钟有效的 8 位数字配对码,供新老师现场输入绑定(彻底支持多教师现场共享大屏) /// [HttpPost("request-pairing")] [HttpPost("pair-code")] public async Task RequestPairingCodeAsync() { var deviceIdStr = Request.Headers["X-Device-Id"].FirstOrDefault(); var deviceToken = Request.Headers["X-Device-Token"].FirstOrDefault(); if (string.IsNullOrWhiteSpace(deviceIdStr) || string.IsNullOrWhiteSpace(deviceToken)) { return Unauthorized(new { success = false, message = "缺少设备鉴权凭据 (X-Device-Id / X-Device-Token)" }); } var device = await _securityService.ValidateDeviceAsync(deviceIdStr, deviceToken); if (device == null) { return Unauthorized(new { success = false, message = "设备鉴权失败或设备不存在" }); } var deviceGuid = PairingService.ToDeviceGuid(device.Id); var pairingCode = await _pairingService.ActivateTemporaryPairingAsync(deviceGuid, TimeSpan.FromMinutes(10)); await _deviceNotificationService.NotifyScreenEnterPairingModeAsync(deviceGuid, pairingCode, 600); _logger.LogInformation("Device {DeviceId} locally requested temporary pairing code {Code} (TTL: 600s)", device.Id, pairingCode); return Ok(new { success = true, pairingCode, ttlSeconds = 600, deviceId = device.Id }); } /// /// Turn 117: 教室大屏硬件无感自动引导接口(零激活码体系) /// 无论首次安装还是重新安装,大屏硬件开机自动初始化/恢复凭据,并获取当前有效 8 位配对码 /// [HttpPost("bootstrap")] public async Task BootstrapDeviceAsync([FromBody] DeviceBootstrapRequestDto req) { try { var (device, rawToken) = await _securityService.EnsureDeviceProvisionedAsync(req); var deviceGuid = PairingService.ToDeviceGuid(device.Id); var activeBindings = await _dbContext.TeacherDeviceBindings .Where(b => b.DeviceId == deviceGuid && b.IsActive) .ToListAsync(); bool isBound = activeBindings.Count > 0; var classDisplayName = activeBindings.FirstOrDefault()?.ClassAlias ?? "教学大屏"; var pairingCode = await _pairingService.ActivateTemporaryPairingAsync(deviceGuid, TimeSpan.FromMinutes(10)); await _deviceNotificationService.NotifyScreenEnterPairingModeAsync(deviceGuid, pairingCode, 600); _logger.LogInformation("Device {DeviceId} bootstrapped successfully (IsBound={IsBound}, PairingCode={Code})", device.Id, isBound, pairingCode); return Ok(new { success = true, deviceId = device.Id, deviceToken = rawToken, tenantId = device.TenantId, isBound = isBound, pairingCode = pairingCode, ttlSeconds = 600, classDisplayName = classDisplayName }); } catch (Exception ex) { _logger.LogError(ex, "Failed to bootstrap device"); return StatusCode(500, new { success = false, message = "设备初始化引导异常: " + ex.Message }); } } }