CallCenterHub.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using Hotline.Caches;
  2. using Hotline.Users;
  3. using Microsoft.AspNetCore.SignalR;
  4. using XF.Domain.Authentications;
  5. using XF.Domain.Exceptions;
  6. namespace Hotline.Api.Realtimes;
  7. public class CallCenterHub : Hub
  8. {
  9. private readonly ISessionContext _sessionContext;
  10. private readonly IWorkRepository _workRepository;
  11. private readonly IUserCacheManager _userCacheManager;
  12. public CallCenterHub(
  13. ISessionContext sessionContext,
  14. IWorkRepository workRepository,
  15. IUserCacheManager userCacheManager)
  16. {
  17. _sessionContext = sessionContext;
  18. _workRepository = workRepository;
  19. _userCacheManager = userCacheManager;
  20. }
  21. /// <summary>
  22. /// Called when a new connection is established with the hub.
  23. /// </summary>
  24. /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the asynchronous connect.</returns>
  25. public override async Task OnConnectedAsync()
  26. {
  27. var userId = _sessionContext.RequiredUserId;
  28. var work = _userCacheManager.GetWorkByUser(userId);
  29. if (work == null)
  30. throw new UserFriendlyException($"未查询到上班记录, userId: {userId}");
  31. work.SignalRId = Context.ConnectionId;
  32. await _workRepository.UpdateAsync(work, Context.ConnectionAborted);
  33. _userCacheManager.UpdateWorkByUser(work);
  34. await base.OnConnectedAsync();
  35. }
  36. /// <summary>Called when a connection with the hub is terminated.</summary>
  37. /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the asynchronous disconnect.</returns>
  38. public override Task OnDisconnectedAsync(Exception? exception)
  39. {
  40. return base.OnDisconnectedAsync(exception);
  41. }
  42. }