Ejemplo n.º 1
0
        public async Task <ActionResult <ChatRoomViewModel> > Private([FromQuery] string chatRoomId)
        {
            try
            {
                ChatRoomDto chatRoom = await this.chatService.GetOrCreatePrivateRoomWith(chatRoomId);

                if (chatRoom == null)
                {
                    return(NotFound());
                }

                String currUserId = identity.CurrentUserId;

                ChatRoomViewModel model = mapper.Map <ChatRoomDto, ChatRoomViewModel>(chatRoom);

                return(model);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //ToDo log error
                //logger.Error("{0}",ex.ToString());
                return(BadRequest());
            }
        }
Ejemplo n.º 2
0
        public async Task <ChatRoomDto> GetRoomById(int chatRoomId)
        {
            var chatRoom = await _uow.ChatRoom.GetChatRoomById(chatRoomId);

            var response = new ChatRoomDto
            {
                Id       = chatRoom.Id,
                Name     = chatRoom.Name,
                Type     = chatRoom.Type,
                Users    = new List <UserDto>(),
                Messages = new List <MessageDto>()
            };

            foreach (var member in chatRoom.Users)
            {
                response.Users.Add(new UserDto
                {
                    Id       = member.UserId,
                    UserName = member.User.UserName
                });
            }

            foreach (var message in chatRoom.Messages)
            {
                response.Messages.Add(new MessageDto
                {
                    Id        = message.Id,
                    Name      = message.Name,
                    Text      = message.Text,
                    Timestamp = message.Timestamp
                });
            }

            return(response);
        }
Ejemplo n.º 3
0
        public ChatViewModel(ChatService wsService, ChatFacade facade)
        {
            ChatFacade  = facade;
            CurrentUser = new UserDto();
            ChatRooms   = new List <ChatRoomDto>();
            Messages    = new List <ChatMessageDto>();
            CurrentRoom = new ChatRoomDto();

            Service = wsService;
        }
Ejemplo n.º 4
0
 public IEnumerable <ChatRoomDto> ListChatRooms()
 {
     return(_db.ChatRooms.ToList()
            .OrderByDescending(room => room.Created)
            .Select(room =>
     {
         ChatRoomDto dto = new ChatRoomDto();
         dto.Id = room.Id;
         dto.Name = room.Name;
         return dto;
     }));
 }
Ejemplo n.º 5
0
        /// <summary>
        /// 创建房间
        /// </summary>
        /// <param name="uid">用户ID</param>
        /// <param name="roomDto">用户输入的用于创建房间的信息</param>
        /// <returns>表示异步创建房间的任务,如果创建失败则返回错误信息</returns>
        public async Task <ChatRoomCreateResponseDto> CreateRoomAsync(int uid, ChatRoomDto roomDto)
        {
            // 防止用户打开多个窗口创建房间
            var error = await ApplyForCreatingRoomAsync(uid);

            if (!string.IsNullOrEmpty(error))
            {
                return(new ChatRoomCreateResponseDto
                {
                    Error = error,
                    CloseModalIfError = true
                });
            }
            try
            {
                var room = new ChatRoom
                {
                    OwnerId     = uid,
                    Name        = roomDto.Name,
                    MaxUsers    = roomDto.MaxUsers,
                    IsEncrypted = roomDto.IsEncrypted,
                    IsPermanent = roomDto.IsPermanent,
                    IsHidden    = roomDto.IsHidden,
                    AllowGuest  = roomDto.AllowGuest
                };

                // 如果房间被加密
                if (roomDto.IsEncrypted)
                {
                    Guid salt = Guid.NewGuid();
                    room.Salt         = salt.ToString();
                    room.PasswordHash = PasswordHelper.GeneratePasswordHash(roomDto.Password, room.Salt);
                }

                _dbContext.ChatRoom.Add(room);
                await _dbContext.SaveChangesAsync();

                return(new ChatRoomCreateResponseDto
                {
                    RoomId = HashidsHelper.Encode(room.Id)
                });
            }
            catch (Exception)
            {
                // 因为是多线程,任然可能发生异常
                // 房间名重复
                return(new ChatRoomCreateResponseDto
                {
                    Error = _msg.GetMessage("E003", "房间名"),
                    CloseModalIfError = false
                });
            }
        }
Ejemplo n.º 6
0
        public async Task <ActionResult <ChatRoomViewModel> > Invite([FromBody] InviteInput input)
        {
            ChatRoomDto room = await this.chatService.InviteToRoomAsync(input.UserId, input.ChatRoomId);

            if (room == null)
            {
                return(BadRequest());
            }

            ChatRoomViewModel model = mapper.Map <ChatRoomDto, ChatRoomViewModel>(room);

            return(model);
        }
Ejemplo n.º 7
0
        public async Task <ChatRoomDto> CreateChatRoom(ChatRoomDto room)
        {
            var cRoom = _mapper.Map <ChatRoom>(room);

            cRoom.Id = Guid.NewGuid();
            bool result = await _repo.AddRoom(cRoom);

            if (result)
            {
                return(room = _mapper.Map <ChatRoomDto>(cRoom));
            }

            return(null);
        }
Ejemplo n.º 8
0
        public async Task <ChatRoomDto> InviteToRoomAsync(string userId, string roomId)
        {
            if (String.IsNullOrEmpty(userId))
            {
                throw new ArgumentNullException(nameof(userId));
            }

            if (String.IsNullOrEmpty(roomId))
            {
                throw new ArgumentNullException(nameof(roomId));
            }

            if (userId == identityService.CurrentUserId)
            {
                throw new ArgumentException("User cannot invite himself to chat room", nameof(userId));
            }

            UserEntity user = await this.userRepo.FindByIdAsync(userId);

            if (user == null)
            {
                throw new Exception($"Cannot find user with Id {userId}");
            }

            //var room = await this.roomRepo.FindByIdAsync(roomId);

            //if (room == null)
            //{
            //    throw new Exception($"Cannot find room with Id {roomId}");
            //}

            await roomRepo.AddParticipantsAsync(roomId, new[] { userId });

            var room = await this.roomRepo.FindByIdAsync(roomId);

            ChatRoomDto model = mapper.Map <ChatRoomEntity, ChatRoomDto>(room);

            await notificator.Notificate(new ChatJoinNoitification(new NewChatUser
            {
                Room = model,
                User = mapper.Map <UserEntity, UserDto>(user)
            }, model.Participants.Select(x => x.Id).Where(x => String.Compare(x, user.Id, true) != 0).ToArray()));

            await notificator.Notificate(new NewChatNotification(model, new[] { user.Id }));

            return(model);
        }
Ejemplo n.º 9
0
        public async Task <ChatRoomDto> AddChatRoom([FromBody] ChatRoomDto chatRoom)
        {
            chatRoom.Id = Guid.NewGuid().ToString();
            var room = new ChatRoom
            {
                Id      = chatRoom.Id,
                Name    = chatRoom.Name,
                Created = DateTime.Now
            };

            _db.ChatRooms.Add(room);
            _db.SaveChanges();

            await _hub.Clients.All.SendAsync("NewChatRoom", chatRoom);

            return(chatRoom);
        }
Ejemplo n.º 10
0
 public async Task <IHttpActionResult> CreateRoom(ChatRoomDto room)
 {
     try
     {
         if (ModelState.IsValid)
         {
             return(Ok(await _chatManager.CreateChatRoom(room)));
         }
         else
         {
             return(BadRequest(ModelState));
         }
     }
     catch (Exception ex)
     {
         return(InternalServerError(ex));
     }
 }
Ejemplo n.º 11
0
        public async Task <IActionResult> Chat(int id)
        {
            var chatRoom = new ChatRoomDto();

            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.GetAsync(WebApiRouteContans.GetRoomById + id))
                {
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        string apiResponse = await response.Content.ReadAsStringAsync();

                        chatRoom = JsonConvert.DeserializeObject <ChatRoomDto>(apiResponse);
                    }
                }
            }
            return(View(chatRoom));
        }
Ejemplo n.º 12
0
        public async Task <List <ChatRoomDto> > GetRooms()
        {
            var chatRooms = await _uow.ChatRoom.GetChatRooms();


            var list = new List <ChatRoomDto>();

            foreach (var item in chatRooms)
            {
                var user = new ChatRoomDto
                {
                    Id       = item.Id,
                    Name     = item.Name,
                    Type     = item.Type,
                    Users    = new List <UserDto>(),
                    Messages = new List <MessageDto>()
                };

                foreach (var member in item.Users)
                {
                    user.Users.Add(new UserDto
                    {
                        Id       = member.UserId,
                        UserName = member.User.UserName
                    });
                }

                foreach (var message in item.Messages)
                {
                    user.Messages.Add(new MessageDto
                    {
                        Id        = message.Id,
                        Name      = message.Name,
                        Text      = message.Text,
                        Timestamp = message.Timestamp
                    });
                }

                list.Add(user);
            }

            return(list);
        }
Ejemplo n.º 13
0
        public async Task <ChatRoomDto> GetOrCreatePrivateRoomWith(string userId)
        {
            string currentUserId = identityService.CurrentUserId;

            if (currentUserId == userId)
            {
                throw new ArgumentException("Same user error");
            }

            if (!(await this.userRepo.FindByIdAsync(userId) is UserEntity user))
            {
                throw new ArgumentException("User does not exists");
            }

            var privateRoom = await roomRepo.GetPrivateRoomAsync(currentUserId, userId);

            if (privateRoom == null)
            {
                ChatRoomEntity newChatRoom = new ChatRoomEntity
                {
                    IsPrivate   = true,
                    OwnerUserId = currentUserId.ToLower(),
                    UserRooms   = new List <UsersChatRoomsEntity> {
                        new UsersChatRoomsEntity {
                            UserId = currentUserId
                        }, new UsersChatRoomsEntity {
                            UserId = userId
                        }
                    }
                };
                string id = await roomRepo.CreateAsync(newChatRoom);

                privateRoom = await roomRepo.FindByIdAsync(id);
            }

            ChatRoomDto model = mapper.Map <ChatRoomEntity, ChatRoomDto>(privateRoom);

            await notificator.Notificate(new NewChatNotification(model, model.Participants.Select(x => x.Id)));

            return(model);
        }
Ejemplo n.º 14
0
        public async Task CreateRoom()
        {
            if (string.IsNullOrEmpty(NewRoomName))
            {
                return;
            }
            var newChatRoom = new ChatRoomDto
            {
                Name = NewRoomName
            };

            newChatRoom.Id = ChatFacade.CreateChatRoom(newChatRoom);
            ChatRooms.Add(newChatRoom);
            NewRoomName = "";

            await Service.ChangeViewModelForConnectionsAsync(
                (ChatViewModel viewModel) => { viewModel.ChatRooms.Add(newChatRoom); },
                ChatFacade.GetAllConnectedUsers()
                .Select(s => s.ConnectionId)
                .ToList());
        }
Ejemplo n.º 15
0
        public static string GetRoomName(this ChatRoomDto room, string currentUserId)
        {
            if (!String.IsNullOrWhiteSpace(room.RoomName))
            {
                return(room.RoomName);
            }

            if (room.IsPrivate)
            {
                var name = room.Participants.FirstOrDefault(x => x.Id != currentUserId)?.UserName;

                if (String.IsNullOrWhiteSpace(name))
                {
                    name = "Empty Chat";
                }

                return(name);
            }

            return(String.Format("# ({1}) {0}", room.Participants.Where(x => x.Id != currentUserId).Aggregate("", (agg, next) => agg += next.UserName + ", ").Trim(' ', ','), room.Participants.Count()));
        }