ChatHub.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. using Microsoft.AspNetCore.Identity;
  2. using Microsoft.AspNetCore.SignalR;
  3. using Microsoft.EntityFrameworkCore;
  4. using MTWorkHR.Application.Filters;
  5. using MTWorkHR.Application.Identity;
  6. using MTWorkHR.Application.Mapper;
  7. using MTWorkHR.Application.Models;
  8. using MTWorkHR.Application.Services;
  9. using MTWorkHR.Core.Entities;
  10. using MTWorkHR.Core.Entities.Base;
  11. using MTWorkHR.Core.Global;
  12. using MTWorkHR.Core.UnitOfWork;
  13. using MTWorkHR.Infrastructure.Entities;
  14. using System;
  15. using System.Linq.Dynamic.Core.Tokenizer;
  16. using System.Security.Claims;
  17. using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
  18. namespace MTWorkHR.API.Chat
  19. {
  20. [AppAuthorize]
  21. public class ChatHub : Hub
  22. {
  23. private readonly IUnitOfWork _unitOfWork;
  24. private readonly GlobalInfo _globalInfo;
  25. //private readonly UserService _userService;
  26. private readonly ApplicationUserManager _userManager;
  27. public ChatHub(IUnitOfWork unitOfWork, GlobalInfo globalInfo, ApplicationUserManager userManager /*, UserService userService*/)
  28. {
  29. _unitOfWork = unitOfWork;
  30. _globalInfo = globalInfo;
  31. // _userService = userService;
  32. _userManager = userManager;
  33. }
  34. public async Task getCompanyUsersList()
  35. {
  36. var companyUsers = await GetAllCompanyEmployees();
  37. await Clients.Caller.SendAsync("getCompanyUsersList", companyUsers);
  38. }
  39. public async Task<List<UserAllDto>> GetAllCompanyEmployees()
  40. {
  41. var employees = await _userManager.GetUsersInRoleAsync("Employee");
  42. var companyId = Context.User.Identities.FirstOrDefault().FindFirst("companyId")?.Value;
  43. var CompanyId = long.Parse(companyId);
  44. var res = employees.Where(e => e.CompanyId == CompanyId).ToList();
  45. var response = MapperObject.Mapper.Map<List<UserAllDto>>(res);
  46. return response;
  47. }
  48. //Simple Test Method
  49. public async Task SendMessageAll(string user, string message)
  50. {
  51. await Clients.All.SendAsync("ReceiveMessage", user, message);
  52. }
  53. public async Task sendMsg(string receiverUserId, string msg)
  54. {
  55. try
  56. {
  57. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  58. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  59. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  60. var receiverUser = allConnections.Item1.FirstOrDefault(c => c.UserId == receiverUserId);
  61. var receiverconnIdDB = receiverUser != null ? receiverUser.SignalrId : "0";
  62. ChatMessage messag = new ChatMessage { Content = msg, ReceiverId = receiverUserId, ReceiverName = receiverUser.UserName ?? "", SenderId = userId, SenderName = userName, IsSeen = false };
  63. await _unitOfWork.ChatMessage.AddAsync(messag);
  64. await _unitOfWork.CompleteAsync();
  65. await Clients.Client(receiverconnIdDB).SendAsync("sendMsgResponse", Context.ConnectionId, msg);
  66. }
  67. catch (Exception e) { }
  68. }
  69. public async Task getAllMessagesByUser(string senderId)
  70. {
  71. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  72. var allmessages = await _unitOfWork.ChatMessage.GetAllWithChildrenAsync(senderId, userId);
  73. // Ensure the query is fully materialized before passing it to SignalR
  74. var messagesList = await allmessages.Item1.ToListAsync();
  75. await Clients.Caller.SendAsync("getAllMessagesByUserResponse", messagesList);
  76. }
  77. public async override Task OnDisconnectedAsync(Exception exception)
  78. {
  79. var email = Context.User?.FindFirst(ClaimTypes.Email)?.Value;
  80. var connections = await _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId);
  81. var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
  82. await _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  83. await _unitOfWork.CompleteAsync();
  84. await Clients.Others.SendAsync("userOff", currUserId);
  85. await base.OnDisconnectedAsync(exception);
  86. }
  87. public override async Task OnConnectedAsync()
  88. {
  89. try
  90. {
  91. string currSignalrID = Context.ConnectionId;
  92. var email = Context.User?.FindFirst(ClaimTypes.Email)?.Value;
  93. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  94. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  95. if (userId != null) //if credentials are correct
  96. {
  97. HubConnection currUser = new HubConnection
  98. {
  99. UserId = userId,
  100. UserName = userName,
  101. SignalrId = currSignalrID,
  102. TimeStamp = DateTime.Now
  103. };
  104. var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  105. await _unitOfWork.CompleteAsync();
  106. ChatUserDto newUser = new ChatUserDto(userId, userName, currSignalrID);
  107. await Clients.Caller.SendAsync("authMeResponseSuccess", newUser);//4Tutorial
  108. await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  109. }
  110. else //if credentials are incorrect
  111. {
  112. await Clients.Caller.SendAsync("authMeResponseFail");
  113. }
  114. }
  115. catch (Exception ex) { }
  116. await base.OnConnectedAsync();
  117. }
  118. public void logOut(string userId)
  119. {
  120. var userIdAuth = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  121. var connections = _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId).Result;
  122. // var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
  123. _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  124. _unitOfWork.CompleteAsync();
  125. Clients.Caller.SendAsync("logoutResponse");
  126. Clients.Others.SendAsync("userOff", userIdAuth);
  127. }
  128. public async Task getOnlineUsers()
  129. {
  130. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  131. var currUserId = allConnections.Item1.Where(c => c.SignalrId == Context.ConnectionId).Select(c => c.UserId).SingleOrDefault();
  132. List<ChatUserDto> onlineUsers = allConnections.Item1
  133. .Where(c => c.UserId != currUserId)
  134. .Select(c =>
  135. new ChatUserDto(c.UserId, c.UserName, c.SignalrId)
  136. ).ToList();
  137. await Clients.Caller.SendAsync("getOnlineUsersResponse", onlineUsers);
  138. }
  139. public async Task authMe(PersonalInfo person)
  140. {
  141. try
  142. {
  143. string currSignalrID = Context.ConnectionId;
  144. //Person tempPerson = ctx.Person.Where(p => p.Username == personInfo.userName && p.Password == personInfo.password)
  145. // .SingleOrDefault();
  146. var companyId = Context.User.Identities.FirstOrDefault().FindFirst("companyId")?.Value;
  147. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  148. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  149. if (userId != null) //if credentials are correct
  150. {
  151. Console.WriteLine("\n" + userName + " logged in" + "\nSignalrID: " + currSignalrID);
  152. HubConnection currUser = new HubConnection
  153. {
  154. UserId = userId,
  155. UserName = userName,
  156. SignalrId = currSignalrID,
  157. TimeStamp = DateTime.Now
  158. };
  159. var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  160. await _unitOfWork.CompleteAsync();
  161. ChatUserDto newUser = new ChatUserDto(userId, userName, currSignalrID);
  162. await Clients.Caller.SendAsync("authMeResponseSuccess", newUser);//4Tutorial
  163. await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  164. }
  165. else //if credentials are incorrect
  166. {
  167. await Clients.Caller.SendAsync("authMeResponseFail");
  168. }
  169. }
  170. catch (Exception e)
  171. {
  172. await Clients.Caller.SendAsync("authMeResponseFail");
  173. }
  174. }
  175. //public async Task reauthMe(string userId)
  176. //{
  177. // string currSignalrID = Context.ConnectionId;
  178. // //ApplicationUser tempPerson = ctx.Person.Where(p => p.Id == personId)
  179. // // .SingleOrDefault();
  180. // if (userId == _globalInfo.UserId) //if credentials are correct
  181. // {
  182. // Console.WriteLine("\n" + _globalInfo.UserName + " logged in" + "\nSignalrID: " + currSignalrID);
  183. // HubConnection currUser = new HubConnection
  184. // {
  185. // UserId = _globalInfo.UserId,
  186. // SignalrId = currSignalrID,
  187. // TimeStamp = DateTime.Now
  188. // };
  189. // var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  190. // await _unitOfWork.CompleteAsync();
  191. // ChatUserDto newUser = new ChatUserDto(_globalInfo.UserId, _globalInfo.UserName, currSignalrID);
  192. // await Clients.Caller.SendAsync("reauthMeResponse", newUser);//4Tutorial
  193. // await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  194. // }
  195. //} //end of reauthMe
  196. }
  197. public class PersonalInfo
  198. {
  199. public string userName { get; set; }
  200. public string password { get; set; }
  201. public string userId { get; set; }
  202. }
  203. }