using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.Cors; using TypedSignalR.Client; using Tapper; using server.Services; #pragma warning disable 1998 namespace server.Hubs; [Hub] public interface IProgressHub { Task Join(string taskId); Task Leave(string taskId); Task GetProgress(string taskId); } [Receiver] public interface IProgressReceiver { Task OnReceiveProgress(ProgressInfo message); } [TranspilationSource] public enum ProgressStatus { Running, Completed, Canceled, Failed } [TranspilationSource] public class ProgressInfo { public required string TaskId { get; set; } public required ProgressStatus Status { get; set; } public required double ProgressPercent { get; set; } public required string ErrorMessage { get; set; } }; [Authorize] [EnableCors("SignalR")] public class ProgressHub : Hub, IProgressHub { private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); private readonly ProgressTracker _progressTracker = MsgBus.ProgressTracker; public async Task Join(string taskId) { await Groups.AddToGroupAsync(Context.ConnectionId, taskId); // 发送当前状态(如果存在) var task = _progressTracker.GetTask(taskId); if (task != null) { await Clients.Caller.OnReceiveProgress(task.Value.ToProgressInfo()); } logger.Info($"Client {Context.ConnectionId} joined task {taskId}"); return true; } public async Task Leave(string taskId) { await Groups.RemoveFromGroupAsync(Context.ConnectionId, taskId); logger.Info($"Client {Context.ConnectionId} left task {taskId}"); return true; } public async Task GetProgress(string taskId) { return _progressTracker.GetTask(taskId)?.ToProgressInfo(); } }