ChatHub.cs 13 KB

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