ChatHub.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. using Microsoft.AspNetCore.Identity;
  2. using Microsoft.AspNetCore.SignalR;
  3. using Microsoft.EntityFrameworkCore;
  4. using Microsoft.Extensions.Logging;
  5. using MimeKit;
  6. using MTWorkHR.Application.Filters;
  7. using MTWorkHR.Application.Identity;
  8. using MTWorkHR.Application.Mapper;
  9. using MTWorkHR.Application.Models;
  10. using MTWorkHR.Application.Services;
  11. using MTWorkHR.Core.Entities;
  12. using MTWorkHR.Core.Entities.Base;
  13. using MTWorkHR.Core.Global;
  14. using MTWorkHR.Core.UnitOfWork;
  15. using MTWorkHR.Infrastructure.Entities;
  16. using System;
  17. using System.ComponentModel.Design;
  18. using System.Linq.Dynamic.Core.Tokenizer;
  19. using System.Security.Claims;
  20. using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
  21. namespace MTWorkHR.API.Chat
  22. {
  23. [AppAuthorize]
  24. public class ChatHub : Hub
  25. {
  26. private readonly IUnitOfWork _unitOfWork;
  27. private readonly GlobalInfo _globalInfo;
  28. //private readonly UserService _userService;
  29. private readonly ApplicationUserManager _userManager;
  30. private readonly ILogger<ChatHub> _logger;
  31. public ChatHub(IUnitOfWork unitOfWork, GlobalInfo globalInfo, ApplicationUserManager userManager /*, UserService userService*/, ILogger<ChatHub> logger)
  32. {
  33. _unitOfWork = unitOfWork;
  34. _globalInfo = globalInfo;
  35. // _userService = userService;
  36. _userManager = userManager;
  37. _logger = logger;
  38. }
  39. public async Task GetUsers()
  40. {
  41. var myCompanyUsers = await GetAllCompanyEmployees();
  42. await Clients.Caller.SendAsync("UpdateUserList", myCompanyUsers);
  43. }
  44. public async Task<List<ChatUserDto>> GetAllCompanyEmployees()
  45. {
  46. var response = new List<ChatUserDto>();
  47. try
  48. {
  49. // Get all employees with the "Employee" role
  50. var employees = await _userManager.GetUsersInRoleAsync("Employee");
  51. var companyEmployees = await _userManager.GetUsersInRoleAsync("Employee");
  52. var CompanyId = GetAuthenticatedCompanyId();
  53. var userId = Context.User.Identities.FirstOrDefault()?.FindFirst("uid")?.Value;
  54. // Get all message sender and receiver IDs excluding current user
  55. var allMessages = await GetAllMessages();
  56. var companyUserIds = allMessages
  57. .SelectMany(m => new[] { m.SenderId, m.ReceiverId }).Where(id => id != userId).Distinct().ToHashSet();
  58. // Filter employees who belong to the same company or have messaged the current user
  59. var res = employees.Where(e => e.Id != userId && (e.CompanyId == CompanyId || companyUserIds.Contains(e.Id))).ToList();
  60. //var mappedEmployees = MapperObject.Mapper.Map<List<ChatUserDto>>(res);
  61. // Get online users and map to a dictionary for faster lookups
  62. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  63. var onlineUsers = allConnections.Item1.ToDictionary(c => c.UserId, c => c.SignalrId);
  64. // Retrieve last message data for each employee
  65. foreach (var emp in res)
  66. {
  67. var onlineSignalrId = onlineUsers.TryGetValue(emp.Id, out var signalrId) ? signalrId : null;
  68. var isOnline = onlineSignalrId != null;
  69. var profileImg = ""; // Assuming this is coming from another source if needed
  70. // Retrieve last message and unseen count for the employee
  71. var lastMessage = await GetLastMessage(emp.Id);
  72. // Create ChatUserDto and add to response
  73. response.Add(new ChatUserDto(
  74. emp.Id,
  75. $"{emp.FirstName} {emp.LastName}",
  76. onlineSignalrId,
  77. emp.Email,
  78. isOnline,
  79. profileImg,
  80. lastMessage.Item2,
  81. lastMessage.Item1?.Content,
  82. lastMessage.Item1?.CreateDate,
  83. emp.FirstName,
  84. emp.LastName
  85. ));
  86. }
  87. }
  88. catch (Exception e)
  89. {
  90. _logger.LogError(e, e.Message);
  91. }
  92. return response;
  93. }
  94. private long GetAuthenticatedCompanyId()
  95. {
  96. long CompanyIdLong = 0;
  97. var identity = Context.User?.Identities.FirstOrDefault();
  98. var CompanyId = identity!=null ? identity.FindFirst("companyId")?.Value : "0";
  99. if(CompanyId != null)
  100. {
  101. CompanyIdLong = long.Parse(CompanyId);
  102. }
  103. return CompanyIdLong;
  104. }
  105. // Get previous messages between two users
  106. public async Task GetPreviousMessages(string contactId)
  107. {
  108. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  109. var allmessages = await _unitOfWork.ChatMessage.GetAllWithChildrenAsync(userId, contactId);
  110. // Ensure the query is fully materialized before passing it to SignalR
  111. var messagesList = await allmessages.Item1.ToListAsync();
  112. await Clients.Caller.SendAsync("PreviousMessages", messagesList);
  113. }
  114. // Send a message from one user to another
  115. public async Task SendMessage(string receiverUserId, string msg)
  116. {
  117. try
  118. {
  119. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  120. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  121. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  122. var receiverUser = allConnections.Item1.FirstOrDefault(c => c.UserId == receiverUserId);
  123. var receiverconnIdDB = receiverUser != null ? receiverUser.SignalrId : "0";
  124. ChatMessage messag = new ChatMessage {
  125. Content = msg,
  126. ReceiverId = receiverUserId,
  127. ReceiverName = receiverUser?.UserName ?? "",
  128. SenderId = userId,
  129. SenderName = userName,
  130. IsSeen = false
  131. };
  132. await _unitOfWork.ChatMessage.AddAsync(messag);
  133. await _unitOfWork.CompleteAsync();
  134. await Clients.Client(receiverconnIdDB).SendAsync("ReceiveMessage", messag);
  135. await Clients.Caller.SendAsync("ReceiveMessage", messag);
  136. }
  137. catch (Exception e) { _logger.LogError(e, e.Message); }
  138. }
  139. public async Task<IList<ChatMessage>> GetAllMessages()
  140. {
  141. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  142. var allmessages = await _unitOfWork.ChatMessage.GetAllUserMessagesAsync(userId);
  143. // Ensure the query is fully materialized before passing it to SignalR
  144. var messagesList = await allmessages.Item1.ToListAsync();
  145. return messagesList;
  146. }
  147. public async Task<Tuple<ChatMessage, int>> GetLastMessage(string contactId)
  148. {
  149. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  150. var allmessages = await _unitOfWork.ChatMessage.GetAllWithChildrenAsync(userId, contactId);
  151. // Ensure the query is fully materialized before passing it to SignalR
  152. var lastOne = allmessages.Item1.OrderByDescending(m=> m.Id).FirstOrDefault();
  153. var unseen = allmessages.Item1.Count(m=> m.IsSeen == false);
  154. return new Tuple<ChatMessage, int>( lastOne?? new ChatMessage(), unseen);
  155. }
  156. //----------------------------------------------------------------------
  157. //----------------------------------------------------------------------
  158. //----------------------------------------------------------------------
  159. //Simple Test Method
  160. public async Task SendMessageAll(string user, string message)
  161. {
  162. await Clients.All.SendAsync("ReceiveMessage", user, message);
  163. }
  164. public async override Task OnDisconnectedAsync(Exception exception)
  165. {
  166. var email = Context.User?.FindFirst(ClaimTypes.Email)?.Value;
  167. var connections = await _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId);
  168. var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
  169. await _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  170. await _unitOfWork.CompleteAsync();
  171. await Clients.Others.SendAsync("userOff", currUserId);
  172. await base.OnDisconnectedAsync(exception);
  173. }
  174. public override async Task OnConnectedAsync()
  175. {
  176. try
  177. {
  178. string currSignalrID = Context.ConnectionId;
  179. var email = Context.User?.FindFirst(ClaimTypes.Email)?.Value;
  180. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  181. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  182. if (userId != null) //if credentials are correct
  183. {
  184. //--------------delete
  185. var connections = await _unitOfWork.HubConnection.GetAllByUserAsync(userId);
  186. await _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  187. await _unitOfWork.CompleteAsync();
  188. //
  189. HubConnection currUser = new HubConnection
  190. {
  191. UserId = userId,
  192. UserName = userName,
  193. SignalrId = currSignalrID,
  194. TimeStamp = DateTime.Now
  195. };
  196. var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  197. await _unitOfWork.CompleteAsync();
  198. ChatUserDto newUser = new ChatUserDto(userId, userName, currSignalrID);
  199. await Clients.Caller.SendAsync("authMeResponseSuccess", newUser);//4Tutorial
  200. await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  201. }
  202. else //if credentials are incorrect
  203. {
  204. await Clients.Caller.SendAsync("authMeResponseFail");
  205. }
  206. }
  207. catch (Exception e) { _logger.LogError(e, e.Message); }
  208. await base.OnConnectedAsync();
  209. }
  210. public void logOut(string userId)
  211. {
  212. var userIdAuth = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  213. var connections = _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId).Result;
  214. // var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
  215. _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  216. _unitOfWork.CompleteAsync();
  217. Clients.Caller.SendAsync("logoutResponse");
  218. Clients.Others.SendAsync("userOff", userIdAuth);
  219. }
  220. public async Task getOnlineUsers()
  221. {
  222. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  223. var currUserId = allConnections.Item1.Where(c => c.SignalrId == Context.ConnectionId).Select(c => c.UserId).SingleOrDefault();
  224. List<ChatUserDto> onlineUsers = allConnections.Item1
  225. .Where(c => c.UserId != currUserId)
  226. .Select(c =>
  227. new ChatUserDto(c.UserId, c.UserName, c.SignalrId)
  228. ).ToList();
  229. await Clients.Caller.SendAsync("getOnlineUsersResponse", onlineUsers);
  230. }
  231. public async Task authMe(PersonalInfo person)
  232. {
  233. try
  234. {
  235. string currSignalrID = Context.ConnectionId;
  236. //Person tempPerson = ctx.Person.Where(p => p.Username == personInfo.userName && p.Password == personInfo.password)
  237. // .SingleOrDefault();
  238. var companyId = Context.User.Identities.FirstOrDefault().FindFirst("companyId")?.Value;
  239. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  240. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  241. if (userId != null) //if credentials are correct
  242. {
  243. Console.WriteLine("\n" + userName + " logged in" + "\nSignalrID: " + currSignalrID);
  244. HubConnection currUser = new HubConnection
  245. {
  246. UserId = userId,
  247. UserName = userName,
  248. SignalrId = currSignalrID,
  249. TimeStamp = DateTime.Now
  250. };
  251. var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  252. await _unitOfWork.CompleteAsync();
  253. ChatUserDto newUser = new ChatUserDto(userId, userName, currSignalrID);
  254. await Clients.Caller.SendAsync("authMeResponseSuccess", newUser);//4Tutorial
  255. await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  256. }
  257. else //if credentials are incorrect
  258. {
  259. await Clients.Caller.SendAsync("authMeResponseFail");
  260. }
  261. }
  262. catch (Exception e)
  263. {
  264. await Clients.Caller.SendAsync("authMeResponseFail");
  265. }
  266. }
  267. //public async Task reauthMe(string userId)
  268. //{
  269. // string currSignalrID = Context.ConnectionId;
  270. // //ApplicationUser tempPerson = ctx.Person.Where(p => p.Id == personId)
  271. // // .SingleOrDefault();
  272. // if (userId == _globalInfo.UserId) //if credentials are correct
  273. // {
  274. // Console.WriteLine("\n" + _globalInfo.UserName + " logged in" + "\nSignalrID: " + currSignalrID);
  275. // HubConnection currUser = new HubConnection
  276. // {
  277. // UserId = _globalInfo.UserId,
  278. // SignalrId = currSignalrID,
  279. // TimeStamp = DateTime.Now
  280. // };
  281. // var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  282. // await _unitOfWork.CompleteAsync();
  283. // ChatUserDto newUser = new ChatUserDto(_globalInfo.UserId, _globalInfo.UserName, currSignalrID);
  284. // await Clients.Caller.SendAsync("reauthMeResponse", newUser);//4Tutorial
  285. // await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  286. // }
  287. //} //end of reauthMe
  288. }
  289. public class PersonalInfo
  290. {
  291. public string userName { get; set; }
  292. public string password { get; set; }
  293. public string userId { get; set; }
  294. }
  295. }