HotlineHub.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. using Google.Protobuf.WellKnownTypes;
  2. using Hotline.Caching.Interfaces;
  3. using Hotline.Realtimes;
  4. using Hotline.Share.Dtos.Realtime;
  5. using Hotline.Users;
  6. using Microsoft.AspNetCore.SignalR;
  7. using System.Threading;
  8. using XF.Domain.Authentications;
  9. using XF.Domain.Cache;
  10. using XF.Domain.Exceptions;
  11. namespace Hotline.Api.Realtimes
  12. {
  13. public class HotlineHub : Hub
  14. {
  15. private readonly ISessionContext _sessionContext;
  16. private readonly IWorkRepository _workRepository;
  17. private readonly ITypedCache<RealtimeConnection> _cacheConnection;
  18. private readonly IUserCacheManager _userCacheManager;
  19. public HotlineHub(
  20. ISessionContext sessionContext,
  21. IWorkRepository workRepository,
  22. ITypedCache<RealtimeConnection> cacheConnection,
  23. IUserCacheManager userCacheManager)
  24. {
  25. _sessionContext = sessionContext;
  26. _workRepository = workRepository;
  27. _cacheConnection = cacheConnection;
  28. _userCacheManager = userCacheManager;
  29. }
  30. /// <summary>
  31. /// Called when a new connection is established with the hub.
  32. /// </summary>
  33. /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the asynchronous connect.</returns>
  34. public override async Task OnConnectedAsync()
  35. {
  36. var userId = _sessionContext.UserId;
  37. if (!string.IsNullOrEmpty(userId))
  38. {
  39. //todo 检查是否exists , t:说明可能是断线重连,1.set cache 2.依据缓存加入group f: 1.set cache
  40. //await SetConnectionAsync(new RealtimeConnection(userId, Context.ConnectionId), Context.ConnectionAborted);
  41. var connection = await _cacheConnection.GetAsync(userId, Context.ConnectionAborted);
  42. if (connection == null)
  43. {
  44. await SetConnectionAsync(new RealtimeConnection(userId, Context.ConnectionId), Context.ConnectionAborted);
  45. }
  46. else
  47. {
  48. connection.ConnectionId = Context.ConnectionId;
  49. await SetConnectionAsync(connection, Context.ConnectionAborted);
  50. if (connection.GroupNames.Any())
  51. {
  52. foreach (var groupName in connection.GroupNames)
  53. {
  54. await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
  55. await Clients.Group(groupName)
  56. .SendAsync("Send", $"{Context.ConnectionId} has joined the group {groupName}.");
  57. }
  58. }
  59. }
  60. }
  61. await base.OnConnectedAsync();
  62. }
  63. /// <summary>Called when a connection with the hub is terminated.</summary>
  64. /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the asynchronous disconnect.</returns>
  65. public override async Task OnDisconnectedAsync(Exception? exception)
  66. {
  67. var userId = _sessionContext.UserId;
  68. if (!string.IsNullOrEmpty(userId))
  69. await _cacheConnection.RemoveAsync(userId, default);
  70. await base.OnDisconnectedAsync(exception);
  71. }
  72. public async Task JoinGroupAsync(JoinGroupDto dto)
  73. {
  74. CheckIfConnected();
  75. var userId = _sessionContext.RequiredUserId;
  76. var connection = await GetConnectionAsync(userId, Context.ConnectionAborted);
  77. if (connection is null)
  78. throw new UserFriendlyException($"尚未建立实时服务连接, userId:{userId}", "尚未建立实时服务连接");
  79. connection.GroupNames.Add(dto.GroupName);
  80. connection.GroupNames = connection.GroupNames.Distinct().ToList();
  81. await SetConnectionAsync(connection, Context.ConnectionAborted);
  82. //switch (dto.GroupName)
  83. //{
  84. // case RealtimeGroupNames.CallCenter:
  85. // var work = _userCacheManager.GetWorkByUser(userId);
  86. // if (work == null)
  87. // throw new UserFriendlyException($"未查询到上班记录, userId: {userId}", "未查询到上班记录");
  88. // work.SignalRId = Context.ConnectionId;
  89. // await _workRepository.UpdateAsync(work, Context.ConnectionAborted);
  90. // _userCacheManager.UpdateWorkByUser(work);
  91. // break;
  92. //}
  93. await Groups.AddToGroupAsync(Context.ConnectionId, dto.GroupName);
  94. await Clients.Group(dto.GroupName).SendAsync("Send", $"{Context.ConnectionId} has joined the group {dto.GroupName}.");
  95. }
  96. public async Task JoinGroupUnauthAsync(JoinGroupDto dto)
  97. {
  98. CheckIfConnected();
  99. await Groups.RemoveFromGroupAsync(Context.ConnectionId, dto.GroupName);
  100. await Groups.AddToGroupAsync(Context.ConnectionId, dto.GroupName);
  101. await Clients.Group(dto.GroupName).SendAsync("Send", $"{Context.ConnectionId} has joined the group {dto.GroupName}.");
  102. }
  103. public async Task LeaveGroupAsync(JoinGroupDto dto)
  104. {
  105. CheckIfConnected();
  106. var userId = _sessionContext.RequiredUserId;
  107. var connection = await GetConnectionAsync(userId, Context.ConnectionAborted);
  108. if (connection is null)
  109. throw new UserFriendlyException($"尚未建立实时服务连接, userId:{userId}", "尚未建立实时服务连接");
  110. if (connection.GroupNames.Contains(dto.GroupName))
  111. {
  112. connection.GroupNames.Remove(dto.GroupName);
  113. await SetConnectionAsync(connection, Context.ConnectionAborted);
  114. }
  115. await Groups.RemoveFromGroupAsync(Context.ConnectionId, dto.GroupName);
  116. await Clients.Group(dto.GroupName).SendAsync("Send", $"{Context.ConnectionId} has left the group {dto.GroupName}.");
  117. //check if not in any groups then disconnect the connection
  118. //if (!connection.GroupNames.Any())
  119. // Context.Abort();
  120. }
  121. public async Task LeaveGroupUnauthAsync(JoinGroupDto dto)
  122. {
  123. CheckIfConnected();
  124. await Groups.RemoveFromGroupAsync(Context.ConnectionId, dto.GroupName);
  125. await Clients.Group(dto.GroupName).SendAsync("Send", $"{Context.ConnectionId} has left the group {dto.GroupName}.");
  126. }
  127. /// <summary>
  128. /// 通知大屏坐席状态
  129. /// </summary>
  130. /// <returns></returns>
  131. public async Task SendSeatState(SeatStateDto dto)
  132. {
  133. await Clients.Group(RealtimeGroupNames.BigScreenSeatState).SendAsync("SeatState", dto, Context.ConnectionAborted);
  134. }
  135. #region private
  136. private void CheckIfConnected()
  137. {
  138. if (string.IsNullOrEmpty(Context.ConnectionId))
  139. throw UserFriendlyException.SameMessage("尚未建立实时通信连接");
  140. }
  141. private Task<RealtimeConnection?> GetConnectionAsync(string userId, CancellationToken cancellationToken)
  142. {
  143. return _cacheConnection.GetAsync(userId, cancellationToken);
  144. }
  145. private Task SetConnectionAsync(RealtimeConnection connection, CancellationToken cancellationToken)
  146. {
  147. return _cacheConnection.SetAsync(connection.UserId, connection, TimeSpan.FromDays(7), cancellationToken);
  148. }
  149. #endregion
  150. }
  151. }