HotlineHub.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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.RequiredUserId;
  35. //todo 检查是否exists , t:说明可能是断线重连,1.set cache 2.依据缓存加入group f: 1.set cache
  36. //await SetConnectionAsync(new RealtimeConnection(userId, Context.ConnectionId), Context.ConnectionAborted);
  37. var connection = await _cacheConnection.GetAsync(userId, Context.ConnectionAborted);
  38. if (connection == null)
  39. {
  40. await SetConnectionAsync(new RealtimeConnection(userId, Context.ConnectionId), Context.ConnectionAborted);
  41. }
  42. else
  43. {
  44. connection.ConnectionId = Context.ConnectionId;
  45. await SetConnectionAsync(connection, Context.ConnectionAborted);
  46. if (connection.GroupNames.Any())
  47. {
  48. foreach (var groupName in connection.GroupNames)
  49. {
  50. await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
  51. await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has joined the group {groupName}.");
  52. }
  53. }
  54. }
  55. await base.OnConnectedAsync();
  56. }
  57. /// <summary>Called when a connection with the hub is terminated.</summary>
  58. /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the asynchronous disconnect.</returns>
  59. public override async Task OnDisconnectedAsync(Exception? exception)
  60. {
  61. var userId = _sessionContext.RequiredUserId;
  62. await _cacheConnection.RemoveAsync(userId, default);
  63. await base.OnDisconnectedAsync(exception);
  64. }
  65. public async Task JoinGroupAsync(JoinGroupDto dto)
  66. {
  67. CheckIfConnected();
  68. var userId = _sessionContext.RequiredUserId;
  69. var connection = await GetConnectionAsync(userId, Context.ConnectionAborted);
  70. if (connection is null)
  71. throw new UserFriendlyException($"尚未建立实时服务连接, userId:{userId}", "尚未建立实时服务连接");
  72. connection.GroupNames.Add(dto.GroupName);
  73. connection.GroupNames = connection.GroupNames.Distinct().ToList();
  74. await SetConnectionAsync(connection, Context.ConnectionAborted);
  75. //switch (dto.GroupName)
  76. //{
  77. // case RealtimeGroupNames.CallCenter:
  78. // var work = _userCacheManager.GetWorkByUser(userId);
  79. // if (work == null)
  80. // throw new UserFriendlyException($"未查询到上班记录, userId: {userId}", "未查询到上班记录");
  81. // work.SignalRId = Context.ConnectionId;
  82. // await _workRepository.UpdateAsync(work, Context.ConnectionAborted);
  83. // _userCacheManager.UpdateWorkByUser(work);
  84. // break;
  85. //}
  86. await Groups.AddToGroupAsync(Context.ConnectionId, dto.GroupName);
  87. await Clients.Group(dto.GroupName).SendAsync("Send", $"{Context.ConnectionId} has joined the group {dto.GroupName}.");
  88. }
  89. public async Task LeaveGroupAsync(JoinGroupDto dto)
  90. {
  91. CheckIfConnected();
  92. var userId = _sessionContext.RequiredUserId;
  93. var connection = await GetConnectionAsync(userId, Context.ConnectionAborted);
  94. if (connection is null)
  95. throw new UserFriendlyException($"尚未建立实时服务连接, userId:{userId}", "尚未建立实时服务连接");
  96. if (connection.GroupNames.Contains(dto.GroupName))
  97. {
  98. connection.GroupNames.Remove(dto.GroupName);
  99. await SetConnectionAsync(connection, Context.ConnectionAborted);
  100. }
  101. await Groups.RemoveFromGroupAsync(Context.ConnectionId, dto.GroupName);
  102. await Clients.Group(dto.GroupName).SendAsync("Send", $"{Context.ConnectionId} has left the group {dto.GroupName}.");
  103. //check if not in any groups then disconnect the connection
  104. //if (!connection.GroupNames.Any())
  105. // Context.Abort();
  106. }
  107. #region private
  108. private void CheckIfConnected()
  109. {
  110. if (string.IsNullOrEmpty(Context.ConnectionId))
  111. throw UserFriendlyException.SameMessage("尚未建立实时通信连接");
  112. }
  113. private Task<RealtimeConnection?> GetConnectionAsync(string userId, CancellationToken cancellationToken)
  114. {
  115. return _cacheConnection.GetAsync(userId, cancellationToken);
  116. }
  117. private Task SetConnectionAsync(RealtimeConnection connection, CancellationToken cancellationToken)
  118. {
  119. return _cacheConnection.SetAsync(connection.UserId, connection, TimeSpan.FromDays(7), cancellationToken);
  120. }
  121. #endregion
  122. }
  123. }