Bläddra i källkod

added the chatHub impelementation

zinab_elgendy 1 månad sedan
förälder
incheckning
b1268d5c38

+ 3 - 3
MTWorkHR.Application/Chat/Chat.cs

@@ -16,12 +16,12 @@ namespace MTWorkHR.API.Chat
         }
         public async Task getOnlineUsers()
         {
-            var allConnections = await _unitOfWork.Connection.GetAllAsync();
+            var allConnections = await _unitOfWork.HubConnection.GetAllAsync();
             var currUserId = allConnections.Item1.Where(c => c.SignalrId == Context.ConnectionId).Select(c => c.UserId).SingleOrDefault();
-            List<UserDto> onlineUsers = allConnections.Item1
+            List<ChatUserDto> onlineUsers = allConnections.Item1
                 .Where(c => c.UserId != currUserId)
                 .Select(c =>
-                    new UserDto { Id = c.UserId, UserName = c.UserName /*, c.SignalrId*/ }
+                    new ChatUserDto (c.UserId, c.UserName , c.SignalrId)
                 ).ToList();
             await Clients.Caller.SendAsync("getOnlineUsersResponse", onlineUsers);
         }

+ 99 - 2
MTWorkHR.Application/Chat/ChatHub.cs

@@ -1,21 +1,118 @@
-using Microsoft.AspNetCore.SignalR;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.SignalR;
+using MTWorkHR.Application.Filters;
 using MTWorkHR.Application.Identity;
+using MTWorkHR.Application.Models;
+using MTWorkHR.Core.Entities;
+using MTWorkHR.Core.Entities.Base;
 using MTWorkHR.Core.Global;
 using MTWorkHR.Core.UnitOfWork;
+using MTWorkHR.Infrastructure.Entities;
+using System;
+using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
 
 namespace MTWorkHR.API.Chat
 {
+    [AppAuthorize]
     public class ChatHub : Hub
     {
         private readonly IUnitOfWork _unitOfWork;
+        private readonly GlobalInfo _globalInfo;
 
-        public ChatHub(IUnitOfWork unitOfWork) 
+        public ChatHub(IUnitOfWork unitOfWork, GlobalInfo globalInfo) 
         {
             _unitOfWork = unitOfWork;
+            _globalInfo = globalInfo;
         }
         public async Task SendMessage(string user, string message)
         {
             await Clients.All.SendAsync("ReceiveMessage", user, message);
         }
+
+
+        public override Task OnDisconnectedAsync(Exception exception)
+        {
+            var connections = _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId).Result;
+           var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
+            _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
+            _unitOfWork.CompleteAsync();
+            Clients.Others.SendAsync("userOff", currUserId);
+            return base.OnDisconnectedAsync(exception);
+        }
+
+
+        //2Tutorial
+        public async Task authMe(string userId)
+        {
+            string currSignalrID = Context.ConnectionId;
+            //Person tempPerson = ctx.Person.Where(p => p.Username == personInfo.userName && p.Password == personInfo.password)
+            //    .SingleOrDefault();
+
+            if (userId  == _globalInfo.UserId) //if credentials are correct
+            {
+                Console.WriteLine("\n" + _globalInfo.UserName + " logged in" + "\nSignalrID: " + currSignalrID);
+
+                HubConnection currUser = new HubConnection
+                {
+                    UserId = _globalInfo.UserId,
+                    SignalrId = currSignalrID,
+                    TimeStamp = DateTime.Now
+                };
+                var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
+
+                await _unitOfWork.CompleteAsync();
+
+                ChatUserDto newUser = new ChatUserDto(_globalInfo.UserId, _globalInfo.UserName, currSignalrID);
+                await Clients.Caller.SendAsync("authMeResponseSuccess", newUser);//4Tutorial
+                await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
+            }
+
+            else //if credentials are incorrect
+            {
+                await Clients.Caller.SendAsync("authMeResponseFail");
+            }
+        }
+
+
+        //3Tutorial
+        public async Task reauthMe(string userId)
+        {
+            string currSignalrID = Context.ConnectionId;
+            //ApplicationUser tempPerson = ctx.Person.Where(p => p.Id == personId)
+            //    .SingleOrDefault();
+
+            if (userId == _globalInfo.UserId) //if credentials are correct
+            {
+                Console.WriteLine("\n" + _globalInfo.UserName + " logged in" + "\nSignalrID: " + currSignalrID);
+
+                HubConnection currUser = new HubConnection
+                {
+                    UserId = _globalInfo.UserId,
+                    SignalrId = currSignalrID,
+                    TimeStamp = DateTime.Now
+                };
+                var newConnection = await _unitOfWork.HubConnection.AddAsync(currUser);
+
+                await _unitOfWork.CompleteAsync();
+
+                ChatUserDto newUser = new ChatUserDto(_globalInfo.UserId, _globalInfo.UserName, currSignalrID);
+
+                await Clients.Caller.SendAsync("reauthMeResponse", newUser);//4Tutorial
+                await Clients.Others.SendAsync("userOn", newUser);//4Tutorial
+            }
+        } //end of reauthMe
+
+
+        //4Tutorial
+        public void logOut(Guid personId)
+        {
+            var connections = _unitOfWork.HubConnection.GetAllAsync(Context.ConnectionId).Result;
+           // var currUserId = connections.Item1.Select(c => c.UserId).SingleOrDefault();
+            _unitOfWork.HubConnection.DeleteRangeAsync(connections.Item1.ToList());
+            _unitOfWork.CompleteAsync();
+
+            Clients.Caller.SendAsync("logoutResponse");
+            Clients.Others.SendAsync("userOff", personId);
+        }
     }
 }

+ 22 - 0
MTWorkHR.Application/Dtos/User/ChatUserDto.cs

@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MTWorkHR.Application.Models
+{
+    public class ChatUserDto
+    {
+        public string UserId { get; set; }
+        public string UserName { get; set; }
+        public string ConnectionId { get; set; } //signalrId
+
+        public ChatUserDto(string someId, string someName, string someConnId)
+        {
+            UserId = someId;
+            UserName = someName;
+            ConnectionId = someConnId;
+        }
+    }
+}

+ 1 - 1
MTWorkHR.Core/Entities/Chat/Connection.cs

@@ -6,7 +6,7 @@ using System.Collections.Generic;
 
 namespace MTWorkHR.Core.Entities
 {
-    public partial class Connection : Entity
+    public partial class HubConnection : Entity
     {
         public string UserId { get; set; }
         public string UserName { get; set; }

+ 3 - 2
MTWorkHR.Core/IRepositories/Chat/IConnectionRepository.cs

@@ -8,8 +8,9 @@ using System.Threading.Tasks;
 
 namespace MTWorkHR.Core.IRepositories
 {
-    public interface IConnectionRepository : IRepository<Connection>
+    public interface IHubConnectionRepository : IRepository<HubConnection>
     {
-     
+        Task<Tuple<IQueryable<HubConnection>, int>> GetAllAsync(string connectionId);
+
     }
 }

+ 1 - 1
MTWorkHR.Core/IUnitOfWork/IUnitOfWork.cs

@@ -36,7 +36,7 @@ namespace MTWorkHR.Core.UnitOfWork
         ILoginOTPRepository LoginOTP { get; }
 
         IChatMessageRepository ChatMessage { get; }
-        IConnectionRepository Connection { get; }
+        IHubConnectionRepository HubConnection { get; }
 
         Task<int> CompleteAsync();
 

+ 1 - 1
MTWorkHR.Infrastructure/InfrastructureServiceRegistration.cs

@@ -83,7 +83,7 @@ namespace MTWorkHR.Infrastructure
             services.AddScoped(typeof(ICityRepository), typeof(CityRepository));
             services.AddScoped(typeof(IProjectTeamRepository), typeof(ProjectTeamRepository));
             services.AddScoped(typeof(IChatMessageRepository), typeof(ChatMessageRepository));
-            services.AddScoped(typeof(IConnectionRepository), typeof(ConnectionRepository));
+            services.AddScoped(typeof(IHubConnectionRepository), typeof(ConnectionRepository));
             
 
 

+ 13 - 4
MTWorkHR.Infrastructure/Repositories/Chat/ConnectionRepository.cs

@@ -7,15 +7,24 @@ using MTWorkHR.Core.IRepositories;
 
 namespace MTWorkHR.Infrastructure.Repositories
 {
-    public class ConnectionRepository : Repository<Connection>, IConnectionRepository
+    public class ConnectionRepository : Repository<HubConnection>, IHubConnectionRepository
     {
-        private readonly DbSet<Connection> dbSet;
+        private readonly DbSet<HubConnection> dbSet;
 
         public ConnectionRepository(HRDataContext context) : base(context)
         {
-            dbSet = context.Set<Connection>();
+            dbSet = context.Set<HubConnection>();
         }
-        
+
+        public async Task<Tuple<IQueryable<HubConnection>, int>> GetAllAsync(string connectionId)
+        {
+            var query = dbSet.AsQueryable();
+            var total = await query.CountAsync();
+
+            return new Tuple<IQueryable<HubConnection>, int>(query, total);
+        }
+
        
+
     }
 }

+ 3 - 3
MTWorkHR.Infrastructure/UnitOfWork/UnitOfWork.cs

@@ -39,7 +39,7 @@ namespace MTWorkHR.Infrastructure.UnitOfWorks
         public ILoginOTPRepository LoginOTP { get; }
         public ICityRepository City { get; }
         public IChatMessageRepository ChatMessage { get; }
-        public IConnectionRepository Connection { get; }
+        public IHubConnectionRepository HubConnection { get; }
 
         public UnitOfWork(HRDataContext _context
             , IPermissionRepository permission
@@ -67,7 +67,7 @@ namespace MTWorkHR.Infrastructure.UnitOfWorks
             , IMeetingUserRepository meetingUser
             , IProjectTeamRepository projectTeam
             , IChatMessageRepository chatMessage
-            , IConnectionRepository connection
+            , IHubConnectionRepository connection
 
             )
         {
@@ -97,7 +97,7 @@ namespace MTWorkHR.Infrastructure.UnitOfWorks
             MeetingUser = meetingUser;
             ProjectTeam = projectTeam;
             ChatMessage = chatMessage;
-            Connection = connection;
+            HubConnection = connection;
         }
 
         public async Task<int> CompleteAsync()