ChatHub.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 "Employee" and "Business" roles
  50. var employeesInRole = await _userManager.GetUsersInRoleAsync("Employee");
  51. var businessInRole = await _userManager.GetUsersInRoleAsync("Business");
  52. // Combine employee lists if needed and apply unique filtering based on IDs
  53. var allEmployees = employeesInRole.Union(businessInRole).DistinctBy(e => e.Id).ToList();
  54. var CompanyId = GetAuthenticatedCompanyId();
  55. var userId = Context.User.Identities.FirstOrDefault()?.FindFirst("uid")?.Value;
  56. // Get all message sender and receiver IDs excluding the current user
  57. var allMessages = await GetAllMessages();
  58. var companyUserIds = allMessages
  59. .SelectMany(m => new[] { m.SenderId, m.ReceiverId })
  60. .Where(id => id != userId)
  61. .Distinct()
  62. .ToHashSet();
  63. // Filter all employees by CompanyId or if they have messaged the user
  64. var employeesToChat = allEmployees
  65. .Where(e => e.Id != userId &&
  66. (e.CompanyId == CompanyId || companyUserIds.Contains(e.Id)))
  67. .ToList();
  68. // Get online users and map to a dictionary for faster lookups
  69. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  70. var onlineUsers = allConnections.Item1.ToDictionary(c => c.UserId, c => c.SignalrId);
  71. // Retrieve last message data for each employee
  72. foreach (var emp in employeesToChat)
  73. {
  74. var onlineSignalrId = onlineUsers.TryGetValue(emp.Id, out var signalrId) ? signalrId : null;
  75. var isOnline = onlineSignalrId != null;
  76. var profileImg = ""; // Assuming this is coming from another source if needed
  77. // Retrieve last message and unseen count for the employee
  78. var lastMessage = await GetLastMessage(emp.Id);
  79. // Create ChatUserDto and add to response
  80. response.Add(new ChatUserDto(
  81. emp.Id,
  82. $"{emp.FirstName} {emp.LastName}",
  83. onlineSignalrId,
  84. emp.Email,
  85. isOnline,
  86. profileImg,
  87. lastMessage.Item2,
  88. lastMessage.Item1?.Content,
  89. lastMessage.Item1?.CreateDate,
  90. emp.FirstName,
  91. emp.LastName
  92. ));
  93. }
  94. }
  95. catch (Exception e)
  96. {
  97. _logger.LogError(e, e.Message);
  98. }
  99. return response;
  100. }
  101. private long GetAuthenticatedCompanyId()
  102. {
  103. long CompanyIdLong = 0;
  104. var identity = Context.User?.Identities.FirstOrDefault();
  105. var CompanyId = identity!=null ? identity.FindFirst("companyId")?.Value : "0";
  106. if(CompanyId != null)
  107. {
  108. CompanyIdLong = long.Parse(CompanyId);
  109. }
  110. return CompanyIdLong;
  111. }
  112. // Get previous messages between two users
  113. public async Task GetPreviousMessages(string contactId)
  114. {
  115. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  116. var allmessages = await _unitOfWork.ChatMessage.GetAllWithChildrenAsync(userId, contactId);
  117. // Ensure the query is fully materialized before passing it to SignalR
  118. var messagesList = await allmessages.Item1.ToListAsync();
  119. await Clients.Caller.SendAsync("PreviousMessages", messagesList);
  120. }
  121. // Send a message from one user to another
  122. public async Task SendMessage(string receiverUserId, string msg)
  123. {
  124. try
  125. {
  126. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  127. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  128. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  129. var receiverUser = allConnections.Item1.FirstOrDefault(c => c.UserId == receiverUserId);
  130. var receiverconnIdDB = receiverUser != null ? receiverUser.SignalrId : "0";
  131. ChatMessage messag = new ChatMessage {
  132. Content = msg,
  133. ReceiverId = receiverUserId,
  134. ReceiverName = receiverUser?.UserName ?? "",
  135. SenderId = userId,
  136. SenderName = userName,
  137. IsSeen = false
  138. };
  139. await _unitOfWork.ChatMessage.AddAsync(messag);
  140. await _unitOfWork.CompleteAsync();
  141. await Clients.Client(receiverconnIdDB).SendAsync("ReceiveMessage", messag);
  142. await Clients.Caller.SendAsync("ReceiveMessage", messag);
  143. }
  144. catch (Exception e) { _logger.LogError(e, e.Message); }
  145. }
  146. public async Task<IList<ChatMessage>> GetAllMessages()
  147. {
  148. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  149. var allmessages = await _unitOfWork.ChatMessage.GetAllUserMessagesAsync(userId);
  150. // Ensure the query is fully materialized before passing it to SignalR
  151. var messagesList = await allmessages.Item1.ToListAsync();
  152. return messagesList;
  153. }
  154. public async Task<Tuple<ChatMessage, int>> GetLastMessage(string contactId)
  155. {
  156. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  157. var allmessages = await _unitOfWork.ChatMessage.GetAllWithChildrenAsync(userId, contactId);
  158. // Ensure the query is fully materialized before passing it to SignalR
  159. var lastOne = allmessages.Item1.OrderByDescending(m=> m.Id).FirstOrDefault();
  160. var unseen = allmessages.Item1.Count(m=> m.IsSeen == false);
  161. return new Tuple<ChatMessage, int>( lastOne?? new ChatMessage(), unseen);
  162. }
  163. //----------------------------------------------------------------------
  164. //----------------------------------------------------------------------
  165. //----------------------------------------------------------------------
  166. public async Task<bool> MarkAsSeen(long messageId)
  167. {
  168. //var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  169. var message = await _unitOfWork.ChatMessage.GetByIdAsync(messageId);
  170. message.IsSeen = true;
  171. await _unitOfWork.CompleteAsync();
  172. return true;
  173. }
  174. //Simple Test Method
  175. public async Task SendMessageAll(string user, string message)
  176. {
  177. await Clients.All.SendAsync("ReceiveMessage", user, message);
  178. }
  179. public async override Task OnDisconnectedAsync(Exception exception)
  180. {
  181. var email = Context.User?.FindFirst(ClaimTypes.Email)?.Value;
  182. var connections = await _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId);
  183. var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
  184. await _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  185. await _unitOfWork.CompleteAsync();
  186. await Clients.Others.SendAsync("userOff", currUserId);
  187. await base.OnDisconnectedAsync(exception);
  188. }
  189. public override async Task OnConnectedAsync()
  190. {
  191. try
  192. {
  193. string currSignalrID = Context.ConnectionId;
  194. var email = Context.User?.FindFirst(ClaimTypes.Email)?.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. //--------------delete
  200. var connections = await _unitOfWork.HubConnection.GetAllByUserAsync(userId);
  201. await _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  202. await _unitOfWork.CompleteAsync();
  203. //
  204. HubConnection currUser = new HubConnection
  205. {
  206. UserId = userId,
  207. UserName = userName,
  208. SignalrId = currSignalrID,
  209. TimeStamp = DateTime.Now
  210. };
  211. var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  212. await _unitOfWork.CompleteAsync();
  213. ChatUserDto newUser = new ChatUserDto(userId, userName, currSignalrID);
  214. await Clients.Caller.SendAsync("authMeResponseSuccess", newUser);//4Tutorial
  215. await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  216. }
  217. else //if credentials are incorrect
  218. {
  219. await Clients.Caller.SendAsync("authMeResponseFail");
  220. }
  221. }
  222. catch (Exception e) { _logger.LogError(e, e.Message); }
  223. await base.OnConnectedAsync();
  224. }
  225. public void logOut(string userId)
  226. {
  227. var userIdAuth = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  228. var connections = _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId).Result;
  229. // var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
  230. _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  231. _unitOfWork.CompleteAsync();
  232. Clients.Caller.SendAsync("logoutResponse");
  233. Clients.Others.SendAsync("userOff", userIdAuth);
  234. }
  235. public async Task getOnlineUsers()
  236. {
  237. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  238. var currUserId = allConnections.Item1.Where(c => c.SignalrId == Context.ConnectionId).Select(c => c.UserId).SingleOrDefault();
  239. List<ChatUserDto> onlineUsers = allConnections.Item1
  240. .Where(c => c.UserId != currUserId)
  241. .Select(c =>
  242. new ChatUserDto(c.UserId, c.UserName, c.SignalrId)
  243. ).ToList();
  244. await Clients.Caller.SendAsync("getOnlineUsersResponse", onlineUsers);
  245. }
  246. public async Task authMe(PersonalInfo person)
  247. {
  248. try
  249. {
  250. string currSignalrID = Context.ConnectionId;
  251. //Person tempPerson = ctx.Person.Where(p => p.Username == personInfo.userName && p.Password == personInfo.password)
  252. // .SingleOrDefault();
  253. var companyId = Context.User.Identities.FirstOrDefault().FindFirst("companyId")?.Value;
  254. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  255. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  256. if (userId != null) //if credentials are correct
  257. {
  258. Console.WriteLine("\n" + userName + " logged in" + "\nSignalrID: " + currSignalrID);
  259. HubConnection currUser = new HubConnection
  260. {
  261. UserId = userId,
  262. UserName = userName,
  263. SignalrId = currSignalrID,
  264. TimeStamp = DateTime.Now
  265. };
  266. var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  267. await _unitOfWork.CompleteAsync();
  268. ChatUserDto newUser = new ChatUserDto(userId, userName, currSignalrID);
  269. await Clients.Caller.SendAsync("authMeResponseSuccess", newUser);//4Tutorial
  270. await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  271. }
  272. else //if credentials are incorrect
  273. {
  274. await Clients.Caller.SendAsync("authMeResponseFail");
  275. }
  276. }
  277. catch (Exception e)
  278. {
  279. await Clients.Caller.SendAsync("authMeResponseFail");
  280. }
  281. }
  282. //public async Task reauthMe(string userId)
  283. //{
  284. // string currSignalrID = Context.ConnectionId;
  285. // //ApplicationUser tempPerson = ctx.Person.Where(p => p.Id == personId)
  286. // // .SingleOrDefault();
  287. // if (userId == _globalInfo.UserId) //if credentials are correct
  288. // {
  289. // Console.WriteLine("\n" + _globalInfo.UserName + " logged in" + "\nSignalrID: " + currSignalrID);
  290. // HubConnection currUser = new HubConnection
  291. // {
  292. // UserId = _globalInfo.UserId,
  293. // SignalrId = currSignalrID,
  294. // TimeStamp = DateTime.Now
  295. // };
  296. // var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  297. // await _unitOfWork.CompleteAsync();
  298. // ChatUserDto newUser = new ChatUserDto(_globalInfo.UserId, _globalInfo.UserName, currSignalrID);
  299. // await Clients.Caller.SendAsync("reauthMeResponse", newUser);//4Tutorial
  300. // await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  301. // }
  302. //} //end of reauthMe
  303. }
  304. public class PersonalInfo
  305. {
  306. public string userName { get; set; }
  307. public string password { get; set; }
  308. public string userId { get; set; }
  309. }
  310. }