SignalRNotifyPusher.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using Admin.NET.Core.Service;
  2. using Microsoft.AspNetCore.SignalR;
  3. namespace Admin.NET.Plugin.ApprovalFlow.Service;
  4. /// <summary>
  5. /// SignalR 站内实时推送(P4-16 - 已有实现重构为独立 Pusher)
  6. /// </summary>
  7. public class SignalRNotifyPusher : INotifyPusher, ITransient
  8. {
  9. public string Channel => "SignalR";
  10. private readonly IHubContext<OnlineUserHub, IOnlineUserHub> _hubContext;
  11. private readonly SysCacheService _cacheService;
  12. public SignalRNotifyPusher(
  13. IHubContext<OnlineUserHub, IOnlineUserHub> hubContext,
  14. SysCacheService cacheService)
  15. {
  16. _hubContext = hubContext;
  17. _cacheService = cacheService;
  18. }
  19. public bool IsEnabled(NotifyChannelConfig cfg) => cfg?.SignalR != false;
  20. public async Task<FlowNotifyPushResult> PushAsync(List<long> userIds, FlowNotification notification)
  21. {
  22. try
  23. {
  24. var onlineUsers = _cacheService.HashGetAll<SysOnlineUser>(CacheConst.KeyUserOnline);
  25. var connectionIds = onlineUsers
  26. .Where(u => userIds.Contains(u.Value.UserId))
  27. .Select(u => u.Value.ConnectionId)
  28. .ToList();
  29. if (connectionIds.Count == 0)
  30. return FlowNotifyPushResult.Ok(0);
  31. await _hubContext.Clients.Clients(connectionIds).ReceiveMessage(new
  32. {
  33. title = notification.Title,
  34. message = notification.Content,
  35. type = notification.Type.ToString(),
  36. instanceId = notification.InstanceId,
  37. });
  38. return FlowNotifyPushResult.Ok(connectionIds.Count);
  39. }
  40. catch (Exception ex)
  41. {
  42. return FlowNotifyPushResult.Fail(ex.Message);
  43. }
  44. }
  45. }