ChatHub.cs 13 KB

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