ChatHub.cs 13 KB

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