ChatHub.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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<ChatUserDto>> 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<ChatUserDto>>(res);
  47. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  48. var onlineUsers = allConnections.Item1
  49. .Select(c => new { c.UserId, c.SignalrId }).ToList();
  50. foreach(var emp in res)
  51. {
  52. var online = onlineUsers.FirstOrDefault(u=> u.UserId == emp.Id);
  53. var profileImg = "";
  54. var chatUser = new ChatUserDto(emp.Id, emp.FirstName + " " + emp.LastName, online?.SignalrId, emp.Email, online != null ? true : false, profileImg);
  55. }
  56. return response;
  57. }
  58. private long GetAuthenticatedCompanyId()
  59. {
  60. long CompanyIdLong = 0;
  61. var identity = Context.User?.Identities.FirstOrDefault();
  62. var CompanyId = identity!=null ? identity.FindFirst("companyId")?.Value : "0";
  63. if(CompanyId != null)
  64. {
  65. CompanyIdLong = long.Parse(CompanyId);
  66. }
  67. return CompanyIdLong;
  68. }
  69. // Send a message from one user to another
  70. public async Task sendMsg(string receiverUserId, string msg)
  71. {
  72. try
  73. {
  74. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  75. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  76. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  77. var receiverUser = allConnections.Item1.FirstOrDefault(c => c.UserId == receiverUserId);
  78. var receiverconnIdDB = receiverUser != null ? receiverUser.SignalrId : "0";
  79. ChatMessage messag = new ChatMessage {
  80. Content = msg,
  81. ReceiverId = receiverUserId,
  82. ReceiverName = receiverUser.UserName ?? "",
  83. SenderId = userId,
  84. SenderName = userName,
  85. IsSeen = false
  86. };
  87. await _unitOfWork.ChatMessage.AddAsync(messag);
  88. await _unitOfWork.CompleteAsync();
  89. await Clients.Client(receiverconnIdDB).SendAsync("ReceiveMessage", messag);
  90. await Clients.Caller.SendAsync("ReceiveMessage", messag);
  91. }
  92. catch (Exception e) { }
  93. }
  94. // Get previous messages between two users
  95. public async Task GetPreviousMessages(string contactId)
  96. {
  97. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  98. var allmessages = await _unitOfWork.ChatMessage.GetAllWithChildrenAsync(userId, contactId);
  99. // Ensure the query is fully materialized before passing it to SignalR
  100. var messagesList = await allmessages.Item1.ToListAsync();
  101. await Clients.Caller.SendAsync("PreviousMessages", messagesList);
  102. }
  103. //----------------------------------------------------------------------
  104. //----------------------------------------------------------------------
  105. //----------------------------------------------------------------------
  106. //Simple Test Method
  107. public async Task SendMessageAll(string user, string message)
  108. {
  109. await Clients.All.SendAsync("ReceiveMessage", user, message);
  110. }
  111. public async override Task OnDisconnectedAsync(Exception exception)
  112. {
  113. var email = Context.User?.FindFirst(ClaimTypes.Email)?.Value;
  114. var connections = await _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId);
  115. var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
  116. await _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  117. await _unitOfWork.CompleteAsync();
  118. await Clients.Others.SendAsync("userOff", currUserId);
  119. await base.OnDisconnectedAsync(exception);
  120. }
  121. public override async Task OnConnectedAsync()
  122. {
  123. try
  124. {
  125. string currSignalrID = Context.ConnectionId;
  126. var email = Context.User?.FindFirst(ClaimTypes.Email)?.Value;
  127. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  128. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  129. if (userId != null) //if credentials are correct
  130. {
  131. HubConnection currUser = new HubConnection
  132. {
  133. UserId = userId,
  134. UserName = userName,
  135. SignalrId = currSignalrID,
  136. TimeStamp = DateTime.Now
  137. };
  138. var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  139. await _unitOfWork.CompleteAsync();
  140. ChatUserDto newUser = new ChatUserDto(userId, userName, currSignalrID);
  141. await Clients.Caller.SendAsync("authMeResponseSuccess", newUser);//4Tutorial
  142. await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  143. }
  144. else //if credentials are incorrect
  145. {
  146. await Clients.Caller.SendAsync("authMeResponseFail");
  147. }
  148. }
  149. catch (Exception ex) { }
  150. await base.OnConnectedAsync();
  151. }
  152. public void logOut(string userId)
  153. {
  154. var userIdAuth = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  155. var connections = _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId).Result;
  156. // var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
  157. _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  158. _unitOfWork.CompleteAsync();
  159. Clients.Caller.SendAsync("logoutResponse");
  160. Clients.Others.SendAsync("userOff", userIdAuth);
  161. }
  162. public async Task getOnlineUsers()
  163. {
  164. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  165. var currUserId = allConnections.Item1.Where(c => c.SignalrId == Context.ConnectionId).Select(c => c.UserId).SingleOrDefault();
  166. List<ChatUserDto> onlineUsers = allConnections.Item1
  167. .Where(c => c.UserId != currUserId)
  168. .Select(c =>
  169. new ChatUserDto(c.UserId, c.UserName, c.SignalrId)
  170. ).ToList();
  171. await Clients.Caller.SendAsync("getOnlineUsersResponse", onlineUsers);
  172. }
  173. public async Task authMe(PersonalInfo person)
  174. {
  175. try
  176. {
  177. string currSignalrID = Context.ConnectionId;
  178. //Person tempPerson = ctx.Person.Where(p => p.Username == personInfo.userName && p.Password == personInfo.password)
  179. // .SingleOrDefault();
  180. var companyId = Context.User.Identities.FirstOrDefault().FindFirst("companyId")?.Value;
  181. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  182. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  183. if (userId != null) //if credentials are correct
  184. {
  185. Console.WriteLine("\n" + userName + " logged in" + "\nSignalrID: " + currSignalrID);
  186. HubConnection currUser = new HubConnection
  187. {
  188. UserId = userId,
  189. UserName = userName,
  190. SignalrId = currSignalrID,
  191. TimeStamp = DateTime.Now
  192. };
  193. var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  194. await _unitOfWork.CompleteAsync();
  195. ChatUserDto newUser = new ChatUserDto(userId, userName, currSignalrID);
  196. await Clients.Caller.SendAsync("authMeResponseSuccess", newUser);//4Tutorial
  197. await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  198. }
  199. else //if credentials are incorrect
  200. {
  201. await Clients.Caller.SendAsync("authMeResponseFail");
  202. }
  203. }
  204. catch (Exception e)
  205. {
  206. await Clients.Caller.SendAsync("authMeResponseFail");
  207. }
  208. }
  209. //public async Task reauthMe(string userId)
  210. //{
  211. // string currSignalrID = Context.ConnectionId;
  212. // //ApplicationUser tempPerson = ctx.Person.Where(p => p.Id == personId)
  213. // // .SingleOrDefault();
  214. // if (userId == _globalInfo.UserId) //if credentials are correct
  215. // {
  216. // Console.WriteLine("\n" + _globalInfo.UserName + " logged in" + "\nSignalrID: " + currSignalrID);
  217. // HubConnection currUser = new HubConnection
  218. // {
  219. // UserId = _globalInfo.UserId,
  220. // SignalrId = currSignalrID,
  221. // TimeStamp = DateTime.Now
  222. // };
  223. // var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  224. // await _unitOfWork.CompleteAsync();
  225. // ChatUserDto newUser = new ChatUserDto(_globalInfo.UserId, _globalInfo.UserName, currSignalrID);
  226. // await Clients.Caller.SendAsync("reauthMeResponse", newUser);//4Tutorial
  227. // await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  228. // }
  229. //} //end of reauthMe
  230. }
  231. public class PersonalInfo
  232. {
  233. public string userName { get; set; }
  234. public string password { get; set; }
  235. public string userId { get; set; }
  236. }
  237. }