ChatHub.cs 12 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?.Content;
  57. var lastMsgDate = lastMessage?.CreateDate;
  58. var unseenCount = 0;
  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<ChatMessage> 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. return lastOne?? new ChatMessage();
  115. }
  116. //----------------------------------------------------------------------
  117. //----------------------------------------------------------------------
  118. //----------------------------------------------------------------------
  119. //Simple Test Method
  120. public async Task SendMessageAll(string user, string message)
  121. {
  122. await Clients.All.SendAsync("ReceiveMessage", user, message);
  123. }
  124. public async override Task OnDisconnectedAsync(Exception exception)
  125. {
  126. var email = Context.User?.FindFirst(ClaimTypes.Email)?.Value;
  127. var connections = await _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId);
  128. var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
  129. await _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  130. await _unitOfWork.CompleteAsync();
  131. await Clients.Others.SendAsync("userOff", currUserId);
  132. await base.OnDisconnectedAsync(exception);
  133. }
  134. public override async Task OnConnectedAsync()
  135. {
  136. try
  137. {
  138. string currSignalrID = Context.ConnectionId;
  139. var email = Context.User?.FindFirst(ClaimTypes.Email)?.Value;
  140. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  141. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  142. if (userId != null) //if credentials are correct
  143. {
  144. HubConnection currUser = new HubConnection
  145. {
  146. UserId = userId,
  147. UserName = userName,
  148. SignalrId = currSignalrID,
  149. TimeStamp = DateTime.Now
  150. };
  151. var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  152. await _unitOfWork.CompleteAsync();
  153. ChatUserDto newUser = new ChatUserDto(userId, userName, currSignalrID);
  154. await Clients.Caller.SendAsync("authMeResponseSuccess", newUser);//4Tutorial
  155. await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  156. }
  157. else //if credentials are incorrect
  158. {
  159. await Clients.Caller.SendAsync("authMeResponseFail");
  160. }
  161. }
  162. catch (Exception ex) { }
  163. await base.OnConnectedAsync();
  164. }
  165. public void logOut(string userId)
  166. {
  167. var userIdAuth = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  168. var connections = _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId).Result;
  169. // var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
  170. _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
  171. _unitOfWork.CompleteAsync();
  172. Clients.Caller.SendAsync("logoutResponse");
  173. Clients.Others.SendAsync("userOff", userIdAuth);
  174. }
  175. public async Task getOnlineUsers()
  176. {
  177. var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
  178. var currUserId = allConnections.Item1.Where(c => c.SignalrId == Context.ConnectionId).Select(c => c.UserId).SingleOrDefault();
  179. List<ChatUserDto> onlineUsers = allConnections.Item1
  180. .Where(c => c.UserId != currUserId)
  181. .Select(c =>
  182. new ChatUserDto(c.UserId, c.UserName, c.SignalrId)
  183. ).ToList();
  184. await Clients.Caller.SendAsync("getOnlineUsersResponse", onlineUsers);
  185. }
  186. public async Task authMe(PersonalInfo person)
  187. {
  188. try
  189. {
  190. string currSignalrID = Context.ConnectionId;
  191. //Person tempPerson = ctx.Person.Where(p => p.Username == personInfo.userName && p.Password == personInfo.password)
  192. // .SingleOrDefault();
  193. var companyId = Context.User.Identities.FirstOrDefault().FindFirst("companyId")?.Value;
  194. var userId = Context.User.Identities.FirstOrDefault().FindFirst("uid")?.Value;
  195. var userName = Context.User.Identities.FirstOrDefault().FindFirst("name")?.Value;
  196. if (userId != null) //if credentials are correct
  197. {
  198. Console.WriteLine("\n" + userName + " logged in" + "\nSignalrID: " + currSignalrID);
  199. HubConnection currUser = new HubConnection
  200. {
  201. UserId = userId,
  202. UserName = userName,
  203. SignalrId = currSignalrID,
  204. TimeStamp = DateTime.Now
  205. };
  206. var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  207. await _unitOfWork.CompleteAsync();
  208. ChatUserDto newUser = new ChatUserDto(userId, userName, currSignalrID);
  209. await Clients.Caller.SendAsync("authMeResponseSuccess", newUser);//4Tutorial
  210. await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  211. }
  212. else //if credentials are incorrect
  213. {
  214. await Clients.Caller.SendAsync("authMeResponseFail");
  215. }
  216. }
  217. catch (Exception e)
  218. {
  219. await Clients.Caller.SendAsync("authMeResponseFail");
  220. }
  221. }
  222. //public async Task reauthMe(string userId)
  223. //{
  224. // string currSignalrID = Context.ConnectionId;
  225. // //ApplicationUser tempPerson = ctx.Person.Where(p => p.Id == personId)
  226. // // .SingleOrDefault();
  227. // if (userId == _globalInfo.UserId) //if credentials are correct
  228. // {
  229. // Console.WriteLine("\n" + _globalInfo.UserName + " logged in" + "\nSignalrID: " + currSignalrID);
  230. // HubConnection currUser = new HubConnection
  231. // {
  232. // UserId = _globalInfo.UserId,
  233. // SignalrId = currSignalrID,
  234. // TimeStamp = DateTime.Now
  235. // };
  236. // var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
  237. // await _unitOfWork.CompleteAsync();
  238. // ChatUserDto newUser = new ChatUserDto(_globalInfo.UserId, _globalInfo.UserName, currSignalrID);
  239. // await Clients.Caller.SendAsync("reauthMeResponse", newUser);//4Tutorial
  240. // await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
  241. // }
  242. //} //end of reauthMe
  243. }
  244. public class PersonalInfo
  245. {
  246. public string userName { get; set; }
  247. public string password { get; set; }
  248. public string userId { get; set; }
  249. }
  250. }