ChatHub.cs 11 KB

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