// GET: /<controller>/JoinChatRoom/{id}
        public IActionResult JoinChatRoom(long chatRoomId)
        {
            var chatRoom          = (ChatRoom)_chatRoomService.GetChatRoomById(chatRoomId);
            var chatRoomViewModel = new ChatRoomViewModel(chatRoom);

            return(View("SingleChatRoom", chatRoomViewModel));
        }
Exemple #2
0
        public ActionResult RecentMessages(int chatRoomId, long lastMessageTick)
        {
            int                timeout            = 40;
            int                timeoutCounter     = 0;
            TimeSpan           timeBetweenQueries = new TimeSpan(0, 0, 0, 1);
            bool               hasRequestTimedOut = false;
            DateTime           lastMessage        = new DateTime(lastMessageTick);
            List <ChatMessage> recentMessages     = new List <ChatMessage>();

            while (recentMessages.Count == 0 && hasRequestTimedOut == false)
            {
                recentMessages = (from message in Db.ChatMessages
                                  .Include("Author")
                                  where message.RoomId == chatRoomId &&
                                  message.MessageDate > lastMessage
                                  select message).ToList();
                if (recentMessages.Count == 0)
                {
                    Thread.Sleep(timeBetweenQueries);
                    timeoutCounter++;
                    if (timeoutCounter == timeout)
                    {
                        hasRequestTimedOut = true;
                    }
                }
            }
            ChatRoom          room = Db.ChatRooms.Where(r => r.Id == chatRoomId).FirstOrDefault();
            ChatRoomViewModel vm   = new ChatRoomViewModel()
            {
                Messages   = recentMessages,
                ActiveRoom = room
            };

            return(View(vm));
        }
        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());
            }
        }
        public async Task <JsonResult> Update(ChatRoomViewModel chatRoomViewModel)
        {
            var currentUserId = User.Claims.SingleOrDefault(a => a.Type == "UserId")?.Value;

            chatRoomViewModel = await serviceOfChat.Update(currentUserId, chatRoomViewModel);

            return(Json(chatRoomViewModel));
        }
Exemple #5
0
 private void m_message_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Enter)
     {
         TextBox           textBox   = sender as TextBox;
         ChatRoomViewModel viewmodel = textBox.DataContext as ChatRoomViewModel;
         viewmodel.MessageToSend = textBox.Text;
         viewmodel.CheckAndSendMessage();
     }
 }
Exemple #6
0
 public Client(string ip, int remotePort, int uniqueID, ChatRoomViewModel chatRoomVm)
 {
     this.chatRoomVm = chatRoomVm;
     threads         = new Dictionary <int, TcpClient>()
     {
         { uniqueID + 0, new TcpClient() },
         { uniqueID + 1, new TcpClient() },
         { uniqueID + 2, new TcpClient() },
     };
     ConnectToServer(ip, remotePort);
 }
        public async Task <ActionResult <ChatRoomViewModel> > Room([FromQuery] string chatRoomId)
        {
            var chatRoom = await roomRepo.FindByIdAsync(chatRoomId);

            if (chatRoom == null)
            {
                return(BadRequest("Room not found"));
            }

            ChatRoomViewModel result = mapper.Map <ChatRoomEntity, ChatRoomViewModel>(chatRoom);

            return(result);
        }
        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);
        }
Exemple #9
0
        public async Task <IViewComponentResult> InvokeAsync(string userId, int eventId, string sportName)
        {
            var viewModel = new ChatRoomViewModel
            {
                EventId    = eventId,
                Sport      = sportName,
                SportImage = await this.sportsService.GetImageByNameAsync(sportName),
                Messages   = await this.messagesService.GetAllByEventIdAsync(eventId),
                UserId     = userId,
            };

            return(this.View(viewModel));
        }
Exemple #10
0
        public IActionResult ChatRoom(int chatRoomID)
        {
            ChatRoom chatRoom = _repositoryWrapper.ChatRoom.FindByContition(x => x.ChatRoomID == chatRoomID).Include(x => x.Messages).FirstOrDefault();

            if (chatRoom == null || (Request.Cookies["RoomGuid"] != chatRoom.Guid))
            {
                return(RedirectToAction("Index", "Home"));
            }

            ChatRoomViewModel chatRoomViewModel = new ChatRoomViewModel();

            chatRoomViewModel.CurrentUser = User.Identity.Name;
            chatRoomViewModel.Messages    = chatRoom.Messages.ToList();
            chatRoomViewModel.RoomID      = chatRoomID;
            return(View(chatRoomViewModel));
        }
Exemple #11
0
        // 채팅창 띄우기
        public void ShowRoom(string showedRoomName)
        {
            AddActivateRommList(showedRoomName);

            ChatRoomViewModel roomViewModel = new ChatRoomViewModel();

            roomViewModel.closeEvent += Detach;

            Dictionary <string, ImageSource> friendsImage = new Dictionary <string, ImageSource>();

            foreach (string i in showedRoomName.Split(','))
            {
                friendsImage.Add(i, friendsList.FirstOrDefault(e => e.friendsName == i).friendsImage);
            }

            roomViewModel.Init(userId, activateRoom[showedRoomName], showedRoomName, friendsImage);
        }
        public async Task <ActionResult> Save(ChatRoomViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var viewModel = new ChatRoomViewModel();
                return(View("MessageForm", viewModel));
            }

            if (model.MessageId != 0)
            {
                var msgInDb = await dataservice.GetMessageAsync(model.MessageId);

                msgInDb.Message = model.Message;

                await dataservice.UpdateMessageAsync(msgInDb);
            }
            return(RedirectToAction("Index", "Message"));
        }
Exemple #13
0
        public async Task <bool> DisposeAsync()
        {
            Singleton.getDialogueBox().showSearch(ConfigurationManager.AppSettings["close_message"]);
            unsubscribeEvents();
            ItemViewModel.Dispose();
            ClientViewModel.Dispose();
            QuoteViewModel.Dispose();
            OrderViewModel.Dispose();
            ReferentialViewModel.Dispose();
            AgentViewModel.Dispose();
            NotificationViewModel.Dispose();
            SecurityLoginViewModel.Dispose();
            HomeViewModel.Dispose();
            ChatRoomCurrentView = null;
            await ChatRoomViewModel.DisposeAsync();

            deleteCache();
            return(true);
        }
Exemple #14
0
        public ActionResult OldMessages(int chatRoomId, long firstMessageTick, int count)
        {
            DateTime           firstMessage = new DateTime(firstMessageTick);
            List <ChatMessage> messages     = new List <ChatMessage>();

            messages = (from message in Db.ChatMessages
                        .Include("Author")
                        where message.RoomId == chatRoomId &&
                        message.MessageDate < firstMessage
                        select message).ToList();
            ChatRoom          room = Db.ChatRooms.Where(r => r.Id == chatRoomId).FirstOrDefault();
            ChatRoomViewModel vm   = new ChatRoomViewModel()
            {
                Messages   = messages,
                ActiveRoom = room
            };

            return(View("RecentMessages", vm));
        }
Exemple #15
0
        public ActionResult Index(int id = -1)
        {
            if (id == -1)
            {
                //find the default chat room id
                id = Db.ChatRooms.Where(r => r.SchoolId == CurrentUser.SchoolId)
                     .Where(r => r.IsDefaultRoom == true)
                     .FirstOrDefault()
                     .Id;
            }

            //remove the user from all other rooms by setting last active date to a long time ago
            List <ChatRoomUser> records = Db.ChatRoomUsers.Where(u => u.UserId == CurrentUser.Id).Where(u => u.RoomId != id).ToList();

            foreach (ChatRoomUser record in records)
            {
                record.LastActivity = DateTime.UtcNow.AddDays(-1);
            }

            //Add a chat message indicating that the user has entered the room
            ChatRoomUser userRecord = Db.ChatRoomUsers.Where(u => u.UserId == CurrentUser.Id).Where(u => u.RoomId == id).FirstOrDefault();

            if (userRecord != null)
            {
                if (userRecord.LastActivity < DateTime.UtcNow.Subtract(CHAT_TIMEOUT))
                {
                    ChatMessage message = new ChatMessage()
                    {
                        AuthorId    = CurrentUser.Id,
                        Message     = string.Format("{0} has entered the chat room.", CurrentUser.FirstName),
                        MessageDate = DateTime.UtcNow,
                        RoomId      = id
                    };
                    Db.ChatMessages.Add(message);
                }
            }
            Db.SaveChanges();

            ChatRoomViewModel vm = BuildViewModel(id);

            return(View(vm));
        }
        public static string GetRoomName(this ChatRoomViewModel 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()));
        }
        public async Task <ActionResult> GetMessages()
        {
            var list     = new List <ChatRoomViewModel>();
            var messages = await dataservice.GetMessagesListAsync();

            foreach (var msg in messages)
            {
                var chatRoomModel = new ChatRoomViewModel();
                chatRoomModel.Code = new CodeViewModel()
                {
                    Code = msg.Codes.PinCode, Id = msg.Codes.Id
                };
                chatRoomModel.CodeId    = msg.Codes.Id;
                chatRoomModel.RoomCode  = msg.Codes.PinCode;
                chatRoomModel.Message   = msg.Message;
                chatRoomModel.UserName  = msg.AspNetUsers.UserName;
                chatRoomModel.MessageId = msg.Id;
                list.Add(chatRoomModel);
            }
            return(Json(list, JsonRequestBehavior.AllowGet));
        }
        public async Task <ActionResult> Chat()
        {
            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            var codes = await dataservice.GetCodesListAsync();

            if (user == null || codes.Count() == 0)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var res = CastToCodeViewModel(codes);

            var model = new ChatRoomViewModel()
            {
                UserName = user.UserName,
                Codes    = res,
                CodeId   = res[0].Id
            };

            return(View(model));
        }
Exemple #19
0
        public TypedNotification Post([FromForm] string connectionId)
        {
            if (!String.IsNullOrEmpty(connectionId))
            {
                TypedNotification notification = this.observer.GetMessageOrDefaultAsync(Guid.Parse(connectionId), 1000 * 60);

                if (notification == null)
                {
                    return(null);
                }

                if (notification.Type == AppNotificationType.ChatJoin)
                {
                    var dto = notification.Notification as NewChatUser;
                    ChatJoinViewModel vm = mapper.Map <NewChatUser, ChatJoinViewModel>(dto);

                    return(new TypedNotification(AppNotificationType.ChatJoin, vm));
                }

                if (notification.Type == AppNotificationType.Message)
                {
                    return(new TypedNotification(AppNotificationType.Message, mapper.Map <MessageDto, MessageViewModel>(notification.Notification as MessageDto)));
                }

                if (notification.Type == AppNotificationType.NewChat)
                {
                    var dto = notification.Notification as ChatRoomDto;
                    ChatRoomViewModel vm = mapper.Map <ChatRoomDto, ChatRoomViewModel>(dto);
                    vm.RoomName = dto.GetRoomName(identity.CurrentUserId);

                    return(new TypedNotification(AppNotificationType.NewChat, vm));
                }


                return(notification);
            }

            return(null);
        }
        public ChatPage()
        {
            InitializeComponent();
            viewModel           = new ChatRoomViewModel();
            this.BindingContext = viewModel;
            ScrollListCommand   = new Command(() =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    try
                    {
                        ChatList.ScrollTo((this.BindingContext as ChatRoomViewModel).Messages.Last(), ScrollToPosition.End, false);
                    }
                    catch (Exception)
                    {
                    }
                }


                                               );
            });
        }
        // GET: Message/Edit/5
        public async Task <ActionResult> Edit(int id)
        {
            var msgList = await dataservice.GetMessagesListAsync();

            var codes = await dataservice.GetCodesListAsync();

            var msg = msgList.FirstOrDefault(e => e.Id == id);

            var listCodes = new List <CodeViewModel>();

            foreach (var item in codes)
            {
                var codeModel = new CodeViewModel();
                codeModel.Code = item.PinCode;
                codeModel.Id   = item.Id;
                listCodes.Add(codeModel);
            }

            if (msg == null)
            {
                return(HttpNotFound());
            }

            var viewModel = new ChatRoomViewModel();

            viewModel.CodeId   = (int)msg.PinId;
            viewModel.RoomCode = msg.Codes.PinCode;
            viewModel.Code     = new CodeViewModel()
            {
                Id = msg.Codes.Id, Code = msg.Codes.PinCode
            };;
            viewModel.Message   = msg.Message;
            viewModel.MessageId = msg.Id;
            viewModel.Codes     = listCodes;
            viewModel.UserName  = msg.AspNetUsers.UserName;

            return(View("MessageForm", viewModel));
        }
Exemple #22
0
 public ChatRoom(string UserName, string otherUser, IHubProxy chatHubProxy)
 {
     DataContext = new ChatRoomViewModel(UserName, otherUser, chatHubProxy);
     InitializeComponent();
 }
Exemple #23
0
 private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
 {
     this.ChatRoom = (ChatRoomViewModel)e.NewValue;
 }
Exemple #24
0
        public JsonResult RoomUsers()
        {
            const string chatRoomIdKey      = "ChatRoomId";
            int          chatRoomId         = 0;
            int          timeout            = 20;
            int          timeoutCounter     = 0;
            TimeSpan     timeBetweenQueries = new TimeSpan(0, 0, 0, 2);
            bool         hasRequestTimedOut = false;

            Int32.TryParse(Request[chatRoomIdKey], out chatRoomId);

            //turn JSON data into objects
            List <ChatRoomUserViewModel> users = new List <ChatRoomUserViewModel>();

            foreach (string key in Request.Form.AllKeys)
            {
                //ignore chat room key
                if (key.CompareTo(chatRoomIdKey) != 0)
                {
                    int userId = 0;
                    if (Int32.TryParse(key, out userId))
                    {
                        users.Add(new ChatRoomUserViewModel()
                        {
                            CssClasses = Request[key],
                            Id         = userId
                        });
                    }
                }
            }

            Dictionary <int, int> mergedIdList = new Dictionary <int, int>();
            Dictionary <int, int> originalIds  = new Dictionary <int, int>();
            ChatRoomViewModel     updatedModel = null;

            //capture all users that were active at the time the HTTP request was made
            foreach (ChatRoomUserViewModel user in users)
            {
                //only add visible users
                if (user.IsCssVisible)
                {
                    originalIds.Add(user.Id, user.Id);
                }
            }


            while (hasRequestTimedOut == false)
            {
                updatedModel = BuildViewModel(chatRoomId);

                //Capture all users that are currently active
                Dictionary <int, int> updatedIds = new Dictionary <int, int>();
                foreach (ChatRoomUserViewModel user in updatedModel.Users)
                {
                    if (user.IsCssVisible == true)
                    {
                        updatedIds.Add(user.Id, user.Id);
                    }
                }

                //do the easy diff check first
                if (originalIds.Count != updatedIds.Count)
                {
                    hasRequestTimedOut = true;
                }
                else
                {
                    //merge the list of active and inactive users into a single list
                    mergedIdList = new Dictionary <int, int>();
                    foreach (int key in originalIds.Keys)
                    {
                        if (mergedIdList.ContainsKey(key) == false)
                        {
                            mergedIdList.Add(key, key);
                        }
                    }
                    foreach (int key in updatedIds.Keys)
                    {
                        if (mergedIdList.ContainsKey(key) == false)
                        {
                            mergedIdList.Add(key, key);
                        }
                    }

                    //now, loop through the list of merged keys to find any changes
                    foreach (int key in mergedIdList.Keys)
                    {
                        //If the merged list differs from either the original or updated, that means that
                        //at least one user has left or joined the chat room since the original request was made.
                        //In this case, we need to send back the updated list to the client immediately.
                        if (originalIds.ContainsKey(key) == false || updatedIds.ContainsKey(key) == false)
                        {
                            hasRequestTimedOut = true;
                            break;
                        }
                    }
                }

                //check for a general timeout
                if (hasRequestTimedOut == false)
                {
                    Thread.Sleep(timeBetweenQueries);
                    timeoutCounter++;
                    if (timeoutCounter == timeout)
                    {
                        hasRequestTimedOut = true;
                    }
                }
            }

            var simpleUsers = updatedModel.Users.Select(u => new
            {
                Id         = u.Id,
                CssClasses = u.CssClasses
            });

            return(this.Json(simpleUsers, JsonRequestBehavior.AllowGet));
        }
Exemple #25
0
        public async Task <IActionResult> CreateChatRoom(ChatRoomViewModel viewModel)
        {
            var result = await _chatService.CreateChatRoom(viewModel.Name);

            return(RedirectToAction("JoinChatRoom", new { chatRoomId = result.Output.Id }));
        }
Exemple #26
0
        private ChatRoomViewModel BuildViewModel(int activeRoomId)
        {
            //log the user into the database
            ChatRoomUser cru = Db.ChatRoomUsers
                               .Where(u => u.UserId == CurrentUser.Id)
                               .Where(u => u.RoomId == activeRoomId)
                               .FirstOrDefault();

            if (cru == null)
            {
                cru = new ChatRoomUser()
                {
                    RoomId = activeRoomId,
                    UserId = CurrentUser.Id
                };
                Db.ChatRoomUsers.Add(cru);
            }
            cru.LastActivity = DateTime.UtcNow;
            Db.SaveChanges();

            //get all chat messages that are associated with the requested room and have been issued within the last hour
            List <ChatMessage> chatMessages = (from message in Db.ChatMessages
                                               .Include("Author")
                                               where message.RoomId == activeRoomId
                                               orderby message.MessageDate descending
                                               select message).Take(25).ToList();
            ChatRoom          room = Db.ChatRooms.Where(r => r.Id == activeRoomId).FirstOrDefault();
            ChatRoomViewModel vm   = new ChatRoomViewModel();

            //find the last date that we're returning
            DateTime minDate = DateTime.MinValue.AddDays(1);

            if (chatMessages.Count > 0)
            {
                minDate = chatMessages.LastOrDefault().MessageDate;
            }

            vm.Messages            = chatMessages;
            vm.ActiveRoom          = room;
            vm.InitialDocumentDate = minDate;
            vm.Rooms = Db.ChatRooms.Where(r => r.SchoolId == CurrentUser.SchoolId).ToList();
            vm.Users = new List <ChatRoomUserViewModel>();

            DateTime minActivityDate = DateTime.UtcNow.Subtract(CHAT_TIMEOUT);
            var      roomUsers       = from chatUser in Db.ChatRoomUsers
                                       where chatUser.User.SchoolId == CurrentUser.SchoolId &&
                                       chatUser.RoomId == activeRoomId &&
                                       chatUser.LastActivity > minActivityDate
                                       select chatUser.UserId;
            Dictionary <int, int> activeUsers = new Dictionary <int, int>();

            foreach (int user in roomUsers)
            {
                activeUsers[user] = user;
            }
            foreach (OsbideUser user in Db.Users.Where(u => u.SchoolId == CurrentUser.SchoolId).OrderBy(u => u.FirstName))
            {
                ChatRoomUserViewModel cvm = new ChatRoomUserViewModel(user);
                if (activeUsers.ContainsKey(user.Id))
                {
                    cvm.IsCssVisible = true;
                }

                UrlHelper u   = new UrlHelper(this.ControllerContext.RequestContext);
                string    url = u.Action("Picture", "Profile", new { id = cvm.Id, size = 24 });
                cvm.ProfileImageUrl = url;

                vm.Users.Add(cvm);
            }

            return(vm);
        }
        public async Task <ChatRoomViewModel> Create(string applicationUserIdCurrent, ChatRoomViewModel chatRoomViewModel)
        {
            var applicationUserIds = chatRoomViewModel.Users.Select(u => u.ApplicationUserId).Concat(new string[] { applicationUserIdCurrent }).ToList();
            var chatRoomEntity     = mapper.Map <ChatRoomViewModel, ChatRoomEntity>(chatRoomViewModel);

            chatRoomEntity           = repositoryOfChatRoom.Create(chatRoomEntity);
            chatRoomEntity.UserChats = applicationUserIds.Select(a => {
                var user             = repositoryOfUserProfile.Read(b => b.ApplicationUserId == a);
                var UserChat         = new UserChatEntity();
                UserChat.ChatRoom    = chatRoomEntity;
                UserChat.ChatRoomId  = chatRoomEntity.Id;
                UserChat.UserId      = user.Id;
                UserChat.UserProfile = user;
                return(repositoryOfUserChat.Create(UserChat));
            }).ToList();
            chatRoomViewModel = mapper.Map <ChatRoomEntity, ChatRoomViewModel>(chatRoomEntity);
            return(chatRoomViewModel);
        }
 public ChatRoomView(ChatRoomViewModel viewmodel)
 {
     DataContext = viewmodel;
     InitializeComponent();
 }
        public async Task <ChatRoomViewModel> Update(string applicationUserIdCurrent, ChatRoomViewModel chatRoomViewModel)
        {
            var applicationUserIds = chatRoomViewModel.Users.Select(u => u.ApplicationUserId).Concat(new string[] { applicationUserIdCurrent }).ToList();
            var chatRoomEntity     = mapper.Map <ChatRoomViewModel, ChatRoomEntity>(chatRoomViewModel);

            chatRoomEntity = repositoryOfChatRoom.Read(a => a.Id == chatRoomEntity.Id);
            // delete
            chatRoomEntity.UserChats
            .TakeWhile(userChat => !applicationUserIds.Any(applicationUserId => applicationUserId == userChat.UserProfile.ApplicationUserId))
            .ToList()
            .ForEach(async a => await repositoryOfUserChat.Delete(a));
            // create
            chatRoomEntity.UserChats = applicationUserIds
                                       .TakeWhile(applicationUserId => !chatRoomEntity.UserChats.Any(userChat => userChat.UserProfile.ApplicationUserId == applicationUserId))
                                       .Select(applicationUserId => {
                var user             = repositoryOfUserProfile.Read(b => b.ApplicationUserId == applicationUserId);
                var UserChat         = new UserChatEntity();
                UserChat.ChatRoom    = chatRoomEntity;
                UserChat.ChatRoomId  = chatRoomEntity.Id;
                UserChat.UserId      = user.Id;
                UserChat.UserProfile = user;
                return(UserChat);
            });
            chatRoomEntity    = repositoryOfChatRoom.Update(chatRoomEntity);
            chatRoomViewModel = mapper.Map <ChatRoomEntity, ChatRoomViewModel>(chatRoomEntity);
            return(chatRoomViewModel);
        }