using System.Security.Claims; using ClassNotify.Server.Data; using ClassNotify.Server.Hubs; using ClassNotify.Server.Infrastructure.Correlation; using ClassNotify.Server.Infrastructure.Logging; using ClassNotify.Server.Services; using Microsoft.EntityFrameworkCore; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.SignalR; namespace ClassNotify.Server.Controllers; [ApiController] [Route("api/[controller]")] [Authorize] [EnableRateLimiting("SendLimiter")] public class NotificationController : ControllerBase { private readonly IHubContext _deviceHubContext; private readonly IHubContext _teacherHubContext; private readonly ISecurityService _securityService; private readonly IVisualReceiptService _visualReceiptService; private readonly ICorrelationContext _correlationContext; private readonly ILogger _logger; public NotificationController( IHubContext deviceHubContext, IHubContext teacherHubContext, ISecurityService securityService, IVisualReceiptService visualReceiptService, ICorrelationContext correlationContext, ILogger logger) { _deviceHubContext = deviceHubContext; _teacherHubContext = teacherHubContext; _securityService = securityService; _visualReceiptService = visualReceiptService; _correlationContext = correlationContext; _logger = logger; } /// /// 教师向指定班级下发呼叫通知 (严格校验租户与班级权限) /// [HttpPost("send")] [HttpPost("/api/notifications")] public async Task SendNotification( [FromBody] NotificationDto notification, [FromServices] ClassNotifyDbContext db) { // 1. Extract and validate tenant from authenticated teacher claims var teacherTenantId = User.FindFirst("tenant_id")?.Value; var teacherName = User.FindFirst(ClaimTypes.Name)?.Value ?? "未知老师"; var teacherId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (string.IsNullOrEmpty(teacherTenantId)) { return Unauthorized(new { success = false, message = "未发现合法的租户信息" }); } // Teacher Service Subscription Gate (Turn 110 Commercial Model) // Expired teachers are strictly prohibited from sending new notifications (Urgent emergency broadcast exempt) if (!string.IsNullOrEmpty(teacherId)) { var teacher = await db.Users.FirstOrDefaultAsync(u => u.Id == teacherId); if (teacher != null) { var now = DateTimeOffset.UtcNow; var subState = teacher.IsVipActive(now) ? "VIP" : (teacher.IsTrialActive(now) ? "Trial" : "Expired"); if (subState == "Expired" && notification.Type != ClassNotify.Shared.Enums.NotificationType.Urgent) { return StatusCode(403, new { success = false, code = "SUBSCRIPTION_REQUIRED", message = "教师个人服务订阅已到期,无法发送新通知。请开通正式版服务。" }); } } } if (string.IsNullOrWhiteSpace(notification.ClassId) || string.IsNullOrWhiteSpace(notification.Message)) { return BadRequest(new { success = false, message = "班级编号与通知内容不可为空" }); } // 2. Multi-tenant Scope Validation: Ensure target classroom exists in teacher's tenant! var classroom = await _securityService.GetClassroomAsync(teacherTenantId, notification.ClassId); if (classroom == null) { _logger.LogWarning("Cross-tenant attempt or invalid class: Teacher {TeacherId} (Tenant: {TenantId}) tried to notify Class {ClassId}", teacherId, teacherTenantId, notification.ClassId); return StatusCode(403, new { success = false, message = "无权访问该班级,或班级不属于当前学校" }); } // License Gate (P79 Layer 1): Check if target classroom devices are expired! var tenantDevices = await _securityService.GetTenantDevicesAsync(teacherTenantId); var classDevices = tenantDevices.Where(d => d.ClassroomId == notification.ClassId).ToList(); var targetDevices = classDevices.Where(d => d.IsOnline).ToList(); if (targetDevices.Count == 0) { targetDevices = classDevices; } var validDevices = targetDevices.Where(d => d.LicenseStatus != "Expired").ToList(); if (targetDevices.Count > 0 && validDevices.Count == 0) { // Invariant: LICENSE MUST NEVER BLOCK EMERGENCY BROADCAST! if (notification.Type != ClassNotify.Shared.Enums.NotificationType.Urgent) { return StatusCode(402, new { success = false, licenseExpired = true, message = $"【{classroom.DisplayName}】设备试用/授权已到期,普通班级通知已暂停下发。请联系学校管理员续费。" }); } } // 3. Stamp metadata & Business TTL Policy notification.Id = $"msg_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}_{Guid.NewGuid().ToString("N")[..4]}"; notification.TenantId = teacherTenantId; notification.CreatedAt = DateTimeOffset.UtcNow; if (string.IsNullOrWhiteSpace(notification.CorrelationId)) { notification.CorrelationId = _correlationContext.CorrelationId; } else if (notification.CorrelationId.Length > 32) { notification.CorrelationId = notification.CorrelationId[..32]; } using var logScope = _logger.BeginClassNotifyScope( notification.CorrelationId, teacherTenantId, notification.ClassId, null, notification.Id, "Server.SendNotification"); if (notification.ExpiresAt.HasValue) { if (notification.ExpiresAt.Value <= notification.CreatedAt) { return BadRequest(new { success = false, message = "消息过期时间必须在创建时间之后" }); } // Max TTL cap: 7 days var maxExpiresAt = notification.CreatedAt.AddDays(7); if (notification.ExpiresAt.Value > maxExpiresAt) { notification.ExpiresAt = maxExpiresAt; } } else { // Default TTL based on NotificationType urgency notification.ExpiresAt = notification.Type switch { ClassNotify.Shared.Enums.NotificationType.Call => notification.CreatedAt.AddMinutes(10), ClassNotify.Shared.Enums.NotificationType.Notice => notification.CreatedAt.AddMinutes(60), ClassNotify.Shared.Enums.NotificationType.Urgent => notification.CreatedAt.AddHours(24), _ => notification.CreatedAt.AddMinutes(15) }; } await _securityService.RecordNotificationAsync(notification, teacherId, teacherName); _logger.LogInformation("Teacher {TeacherName} ({TenantId}) sending notification to {ClassName} ({ClassId}): Length={MessageLength}, Type={NotificationType}", teacherName, teacherTenantId, classroom.DisplayName, classroom.Id, notification.Message.Length, notification.Type); // 4. Send to tenant-isolated SignalR classroom group var tenantClassGroup = $"t:{teacherTenantId}:c:{notification.ClassId}"; await _deviceHubContext.Clients.Group(tenantClassGroup).ReceiveNotification(notification); // 5. Broadcast only to teachers of THIS tenant var tenantTeacherGroup = $"t:{teacherTenantId}:teachers"; await _teacherHubContext.Clients.Group(tenantTeacherGroup).OnNewNotificationBroadcast(notification); return Ok(new { success = true, messageId = notification.Id, correlationId = notification.CorrelationId, tenantId = teacherTenantId, classId = notification.ClassId, className = classroom.DisplayName, message = "通知已成功下发至教室大屏" }); } /// /// 获取当前教师所在学校的班级列表 /// [HttpGet("classes")] public async Task GetTeacherClasses() { var tenantId = User.FindFirst("tenant_id")?.Value; if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var classes = await _securityService.GetClassroomsAsync(tenantId); return Ok(classes); } /// /// 获取当前教师所在学校的班级设备健康与在线状态概要 (透传给教师端) /// [HttpGet("classroom-devices")] public async Task GetClassroomDevices() { var tenantId = User.FindFirst("tenant_id")?.Value; if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var devices = await _securityService.GetTenantDevicesAsync(tenantId); var result = devices.Select(d => new { d.DeviceId, d.ClassroomId, d.ClassroomName, d.Hostname, d.IsOnline, d.LastHeartbeat, d.ClientVersion, d.ServiceRunning, d.ClientRunning, d.LicenseTier, d.LicenseStatus, d.RemainingDays, d.RemainingHours, d.LicensedUntil }); return Ok(result); } /// /// 获取当前教师所在学校的历史通知记录与回执 /// [HttpGet("history")] public async Task GetNotificationHistory([FromQuery] string? classId, [FromQuery] int limit = 50) { var tenantId = User.FindFirst("tenant_id")?.Value; var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? ""; if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var list = await _securityService.GetNotificationsAsync(tenantId, classId, limit, userId); return Ok(list); } /// /// 查看指定通知在指定教室设备的视觉回执现场画面 (受权限保护的短效 JPEG) /// [HttpGet("{notificationId}/receipts/{deviceId}/visual-receipt")] [HttpGet("/api/notifications/{notificationId}/receipts/{deviceId}/visual-receipt")] public async Task GetVisualReceipt(string notificationId, string deviceId) { var result = await _visualReceiptService.GetVisualReceiptFileAsync(notificationId, deviceId, User); if (!result.Success) { return StatusCode(result.StatusCode, new { success = false, message = result.ErrorMessage }); } Response.Headers["Cache-Control"] = "private, no-store, max-age=0"; Response.Headers["Pragma"] = "no-cache"; Response.Headers["X-Content-Type-Options"] = "nosniff"; return PhysicalFile(result.FilePath!, "image/jpeg"); } /// /// 撤回/提前关闭正在显示的通知 /// [HttpPost("{id}/cancel")] [HttpPost("/api/notifications/{id}/cancel")] public async Task CancelNotification(string id, CancellationToken ct) { var tenantId = User.FindFirst("tenant_id")?.Value; var userName = User.FindFirst(ClaimTypes.Name)?.Value ?? "未知操作者"; var userRole = User.FindFirst(ClaimTypes.Role)?.Value ?? "Teacher"; var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? ""; var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); CancelNotificationResult result; try { result = await _securityService.CancelNotificationAsync( id, userId, userName, userRole, tenantId, ip, ct); } catch (KeyNotFoundException ex) { return NotFound(new { success = false, message = ex.Message }); } catch (UnauthorizedAccessException ex) { return StatusCode(403, new { success = false, message = ex.Message }); } bool devicePushOk = true; bool teacherPushOk = true; if (!string.IsNullOrEmpty(result.ClassroomId)) { try { var tenantClassGroup = $"t:{result.TenantId}:c:{result.ClassroomId}"; await _deviceHubContext.Clients.Group(tenantClassGroup).CancelNotification(id); } catch (Exception ex) { devicePushOk = false; _logger.LogError(ex, "Failed to broadcast CancelNotification to device group for {NotificationId}", id); } } try { var tenantTeacherGroup = $"t:{result.TenantId}:teachers"; await _teacherHubContext.Clients.Group(tenantTeacherGroup).OnNotificationCancelled(id); } catch (Exception ex) { teacherPushOk = false; _logger.LogError(ex, "Failed to broadcast OnNotificationCancelled to teacher group for {NotificationId}", id); } return Ok(new { success = true, notificationId = id, alreadyCancelled = result.AlreadyCancelled, cancelledAt = result.CancelledAt, realtimeDeviceCloseSent = devicePushOk, realtimeTeacherUpdateSent = teacherPushOk, message = result.AlreadyCancelled ? "通知此前已被撤回" : devicePushOk ? "通知已成功撤回并请求大屏立即关闭" : "通知已撤回;实时关闭信令部分失败,但该通知不会再次补发" }); } /// /// 从当前用户的历史记录中移除指定通知 (Per-user History Dismissal) /// 仅在当前用户视图中隐藏,绝不破坏底层通知、全校设备回执与审计证据 /// [HttpDelete("{id}/history")] [HttpDelete("/api/notifications/{id}/history")] [HttpDelete("{id}")] [HttpDelete("/api/notifications/{id}")] public async Task DeleteNotification(string id, CancellationToken ct) { var tenantId = User.FindFirst("tenant_id")?.Value; var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? ""; if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); try { var ok = await _securityService.DismissNotificationHistoryAsync(id, tenantId, userId, ct); if (!ok) { return NotFound(new { success = false, message = "通知不存在或已被删除" }); } return Ok(new { success = true, notificationId = id, message = "已从历史记录中移除" }); } catch (UnauthorizedAccessException ex) { return StatusCode(403, new { success = false, message = ex.Message }); } } }