ChatHub.cs 12 KB

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