using System.Collections.Concurrent; using System.Security.Cryptography; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Services; public record ClaimResult(bool Success, Guid? DeviceId, string? ErrorCode = null, string? ErrorMessage = null); public interface IPairingService { Task ClaimDeviceAsync(string teacherId, string pairingCode, string? classAlias); Task ActivateTemporaryPairingAsync(Guid deviceId, TimeSpan ttl); Task<(string State, string? PairingCode, int? TtlSeconds, int ActiveTeacherCount)> GetScreenStateAsync(Guid deviceId, bool isOnline); string GenerateInitialPairingCode(Guid deviceId); } public class PairingService : IPairingService { private readonly ClassNotifyDbContext _db; private readonly IConfiguration _config; private readonly ILogger _logger; // DeviceId -> (PairingCode, ExpiresAtUtc) private static readonly ConcurrentDictionary DevicePairingCodes = new(); // PairingCode -> (DeviceId, ExpiresAtUtc) private static readonly ConcurrentDictionary ActiveCodes = new(); public PairingService(ClassNotifyDbContext db, IConfiguration config, ILogger logger) { _db = db; _config = config; _logger = logger; } public string GenerateInitialPairingCode(Guid deviceId) { var code = RandomNumberGenerator.GetInt32(10000000, 100000000).ToString(); var expiresAt = DateTimeOffset.UtcNow.AddMinutes(10); DevicePairingCodes[deviceId] = (code, expiresAt); ActiveCodes[code] = (deviceId, expiresAt); return code; } public Task ActivateTemporaryPairingAsync(Guid deviceId, TimeSpan ttl) { var code = RandomNumberGenerator.GetInt32(10000000, 100000000).ToString(); var expiresAt = DateTimeOffset.UtcNow.Add(ttl); DevicePairingCodes[deviceId] = (code, expiresAt); ActiveCodes[code] = (deviceId, expiresAt); _logger.LogInformation("Activated temporary pairing mode for device {DeviceId}, Code: {Code}, TTL: {Ttl}", deviceId, code, ttl); return Task.FromResult(code); } public static Guid ToDeviceGuid(string deviceId) { if (Guid.TryParse(deviceId, out var g)) return g; using var md5 = MD5.Create(); var hashBytes = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(deviceId)); var hex = Convert.ToHexString(hashBytes).ToLowerInvariant(); return Guid.Parse($"{hex[..8]}-{hex[8..12]}-{hex[12..16]}-{hex[16..20]}-{hex[20..]}"); } public static (bool IsValid, string? CanonicalName, string? ErrorMessage) ValidateAndCanonicalizeClassName(string? input) { if (string.IsNullOrWhiteSpace(input)) { return (false, null, "班级名称不能为空,请填写班级名称。"); } var raw = input.Trim(); if (System.Text.RegularExpressions.Regex.IsMatch(raw, @"[()()\[\]【】{}]")) { return (false, null, "班级名称不能包含括号,请直接填写,例如:高一3班。"); } var canonical = raw.Replace(" ", ""); if (canonical.Length < 2 || canonical.Length > 20) { return (false, null, "班级名称长度必须在 2 至 20 个字符之间。"); } if (!canonical.EndsWith("班")) { return (false, null, "班级名称必须以“班”结尾,例如:高一3班、91班。"); } foreach (var ch in canonical) { bool isDigit = ch >= '0' && ch <= '9'; bool isHan = (ch >= 0x4E00 && ch <= 0x9FFF) || (ch >= 0x3400 && ch <= 0x4DBF); if (!isDigit && !isHan) { return (false, null, "班级名称只能包含汉字和数字,并且必须以“班”结尾,例如:高一3班、91班。"); } } return (true, canonical, null); } public async Task ClaimDeviceAsync(string teacherId, string pairingCode, string? classAlias) { var (isValid, canonicalClassName, errorMessage) = ValidateAndCanonicalizeClassName(classAlias); if (!isValid) { return new ClaimResult(false, null, "INVALID_CLASS_NAME", errorMessage ?? "班级名称不合法"); } var normalizedCode = pairingCode.Replace(" ", "").Replace("-", "").Trim(); if (!ActiveCodes.TryGetValue(normalizedCode, out var pairingInfo) || pairingInfo.ExpiresAtUtc < DateTimeOffset.UtcNow) { return new ClaimResult(false, null, "INVALID_PAIRING_CODE", "配对码不存在或已过期,请查看大屏最新8位配对码"); } var deviceId = pairingInfo.DeviceId; // Check screen quota var screenLimit = _config.GetValue("Product:PersonalScreenLimit", 4); var currentCount = await _db.TeacherDeviceBindings .CountAsync(b => b.TeacherId == teacherId && b.IsActive); if (currentCount >= screenLimit) { return new ClaimResult(false, null, "SCREEN_QUOTA_EXCEEDED", $"您绑定的屏幕数已达上限({screenLimit}块),请先解绑不再使用的屏幕"); } // Check if teacher is already bound var existing = await _db.TeacherDeviceBindings .FirstOrDefaultAsync(b => b.TeacherId == teacherId && b.DeviceId == deviceId && b.IsActive); if (existing != null) { existing.ClassAlias = canonicalClassName; await _db.SaveChangesAsync(); return new ClaimResult(true, deviceId); } // Turn 117 核心业务约束:大屏生命周期内只能被试用账号绑定一次;已被试用过的大屏,其他试用账号禁止重复绑定,仅正式付费教师可绑定 var teacher = await _db.Users.FirstOrDefaultAsync(u => u.Id == teacherId); if (teacher == null) { return new ClaimResult(false, null, "TEACHER_NOT_FOUND", "教师账户不存在"); } var now = DateTimeOffset.UtcNow; bool isVip = teacher.IsVipActive(now); if (!isVip) { // Case 6: 试用到期以后解绑再绑定,不得获得新的 7 天试用 if (teacher.TrialEndsAt != null && teacher.TrialEndsAt.Value <= now) { _logger.LogWarning("Trial device claim rejected: Teacher {TeacherId} trial already expired at {TrialEndsAt}", teacherId, teacher.TrialEndsAt.Value); return new ClaimResult(false, null, "TRIAL_EXPIRED", "您的 7 天免费试用期已结束。如需继续使用,请升级为正式会员。"); } var deviceIdStr = deviceId.ToString(); var rawHex = deviceIdStr.Replace("-", ""); var shortDevId16 = "dev_" + (rawHex.Length >= 16 ? rawHex.Substring(0, 16) : rawHex); var shortDevId8 = "dev_" + (rawHex.Length >= 8 ? rawHex.Substring(0, 8) : rawHex); var device = await _db.Devices.FirstOrDefaultAsync(d => d.Id == deviceIdStr || d.Id == shortDevId16 || d.Id == shortDevId8); var deviceKey = device?.HardwareComponentsHash ?? deviceIdStr; var targetDevId = device?.Id; var existingTrialLedger = await _db.DeviceTrialLedgers .FirstOrDefaultAsync(l => l.OriginalDeviceId == deviceIdStr || (targetDevId != null && l.OriginalDeviceId == targetDevId) || (!string.IsNullOrEmpty(deviceKey) && l.DeviceTrialKey == deviceKey)); // Case 8: 教师 A 已通过大屏 X 消费 Trial,教师 B 尝试通过同一大屏 X 再获 Trial 必须拒绝 if (existingTrialLedger != null && existingTrialLedger.OriginalUserId != teacherId && existingTrialLedger.OverrideState != "Granted") { _logger.LogWarning("Trial device claim rejected: Screen {DeviceId} (Key: {Key}) already consumed trial by {OrigUser}", deviceId, deviceKey, existingTrialLedger.OriginalUserId); return new ClaimResult(false, null, "TRIAL_ALREADY_USED_ON_DEVICE", "该大屏设备已被试用账号绑定过,免费试用名额已耗尽。请使用正式授权账号绑定。"); } // Case 2: 第一次成功使用 Trial 绑定物理大屏,设置 TrialEndsAt = now + 7 days // Case 5: 第二天重新绑定同一物理设备,TrialEndsAt 必须保持第一次的值,禁止更新为 now + 7 days if (teacher.TrialEndsAt == null) { teacher.TrialEndsAt = now.AddDays(7); _logger.LogInformation("Teacher {TeacherId} bound first screen {DeviceId}. Started 7-day trial until {TrialEndsAt}", teacherId, deviceId, teacher.TrialEndsAt); } if (existingTrialLedger == null) { _db.DeviceTrialLedgers.Add(new DeviceTrialLedger { Id = $"dtl_{Guid.NewGuid():N}".Substring(0, 24), DeviceTrialKey = deviceKey, OriginalDeviceId = targetDevId ?? deviceIdStr, OriginalTenantId = teacher.TenantId ?? "default", OriginalUserId = teacherId, FirstTrialStartedAtUtc = now, TrialEndsAtUtc = teacher.TrialEndsAt ?? now.AddDays(7), Status = "Active" }); if (device != null) { device.TrialUsed = true; } } } var binding = new TeacherDeviceBinding { Id = Guid.NewGuid(), TeacherId = teacherId, DeviceId = deviceId, ClassAlias = canonicalClassName, IsActive = true, BoundAt = DateTimeOffset.UtcNow }; _db.TeacherDeviceBindings.Add(binding); await _db.SaveChangesAsync(); // Invalidate consumed pairing code immediately to prevent replay attacks (Turn 108 requirement) ActiveCodes.TryRemove(normalizedCode, out _); DevicePairingCodes.TryRemove(deviceId, out _); _logger.LogInformation("Teacher {TeacherId} successfully claimed screen {DeviceId}", teacherId, deviceId); return new ClaimResult(true, deviceId); } public async Task<(string State, string? PairingCode, int? TtlSeconds, int ActiveTeacherCount)> GetScreenStateAsync(Guid deviceId, bool isOnline) { if (!isOnline) { return ("OFFLINE", null, null, 0); } var activeTeacherCount = await _db.TeacherDeviceBindings .CountAsync(b => b.DeviceId == deviceId && b.IsActive); var now = DateTimeOffset.UtcNow; var hasActiveCode = DevicePairingCodes.TryGetValue(deviceId, out var codeInfo) && codeInfo.ExpiresAtUtc > now; if (activeTeacherCount == 0) { // WAITING_FOR_FIRST_BIND: auto enter pairing mode if (!hasActiveCode) { var newCode = GenerateInitialPairingCode(deviceId); return ("WAITING_FOR_FIRST_BIND", newCode, 600, 0); } var remaining = (int)(codeInfo.ExpiresAtUtc - now).TotalSeconds; return ("WAITING_FOR_FIRST_BIND", codeInfo.Code, remaining > 0 ? remaining : 0, 0); } // RUNNING: UI 配对区域常驻,Code 必须自动保持有效以便其他教师协同绑定 if (!hasActiveCode) { var newCode = GenerateInitialPairingCode(deviceId); return ("RUNNING", newCode, 600, activeTeacherCount); } var remainingActive = (int)(codeInfo.ExpiresAtUtc - now).TotalSeconds; return ("RUNNING", codeInfo.Code, remainingActive > 0 ? remainingActive : 0, activeTeacherCount); } }