CallCenterHub.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using CallCenter.Caches;
  2. using CallCenter.Realtimes;
  3. using CallCenter.Users;
  4. using Microsoft.AspNetCore.SignalR;
  5. using XF.Domain.Dependency;
  6. using XF.Domain.Exceptions;
  7. using XF.Domain.Https;
  8. namespace CallCenter.Api.Realtimes;
  9. public class CallCenterHub : Hub
  10. {
  11. private readonly ISessionContext _sessionContext;
  12. private readonly IWorkRepository _workRepository;
  13. public CallCenterHub(ISessionContext sessionContext, IWorkRepository workRepository)
  14. {
  15. _sessionContext = sessionContext;
  16. _workRepository = workRepository;
  17. }
  18. /// <summary>
  19. /// Called when a new connection is established with the hub.
  20. /// </summary>
  21. /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the asynchronous connect.</returns>
  22. public override async Task OnConnectedAsync()
  23. {
  24. var userId = _sessionContext.RequiredUserId;
  25. var work = await _workRepository.GetCurrentWorkByUserAsync(userId, Context.ConnectionAborted);
  26. if (work == null)
  27. throw new UserFriendlyException($"未查询到上班记录, userId: {userId}");
  28. work.SignalRId = Context.ConnectionId;
  29. await _workRepository.UpdateAsync(work, Context.ConnectionAborted);
  30. //todo 清理对应work cache
  31. await base.OnConnectedAsync();
  32. }
  33. /// <summary>Called when a connection with the hub is terminated.</summary>
  34. /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the asynchronous disconnect.</returns>
  35. public override Task OnDisconnectedAsync(Exception? exception)
  36. {
  37. //todo 1.清理user与connectionId关联关系记录
  38. return base.OnDisconnectedAsync(exception);
  39. }
  40. }
  41. public class RealtimeService : IRealtimeService, IScopeDependency
  42. {
  43. private readonly IHubContext<CallCenterHub> _hubContext;
  44. private readonly IUserCacheManager _userCacheManager;
  45. public RealtimeService(IHubContext<CallCenterHub> hubContext, IUserCacheManager userCacheManager)
  46. {
  47. _hubContext = hubContext;
  48. _userCacheManager = userCacheManager;
  49. }
  50. public async Task RingAsync(string userId, RingDto dto, CancellationToken cancellationToken)
  51. {
  52. var work = _userCacheManager.GetWorkByUser(userId);
  53. if (string.IsNullOrEmpty(work.SignalRId))
  54. throw new UserFriendlyException("无效signalr.connectionId");
  55. await _hubContext.Clients.Client(work.SignalRId).SendAsync("Ring", dto, cancellationToken);
  56. }
  57. }