HotlineHub.cs 6.9 KB

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