Esempio n. 1
0
        public async Task CreateConversation(User sender, User recipient, Message newMessage)
        {
            UserConversation userConvo = await _conversationRepo.RetrieveUserConversation(sender.Id, recipient.Id);

            if (userConvo != null)
            {
                Conversation convo = await _conversationRepo.Retrieve(userConvo.ConversationsId);

                newMessage.Conversation = convo;
                await _messageRepo.Create(newMessage);

                return;
            }

            Conversation newConvo = new Conversation {
            };

            newConvo.UserConversations = new List <UserConversation> {
                new UserConversation {
                    Conversation = newConvo,
                    User         = sender
                },
                new UserConversation {
                    Conversation = newConvo,
                    User         = recipient
                }
            };

            newConvo.Messages = new List <Message> {
                newMessage
            };

            await _conversationRepo.Create(newConvo);
        }
Esempio n. 2
0
        /// <summary>
        /// Update user conversation id
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userConversation"></param>
        /// <returns></returns>
        public async Task <int> Update(int id, UserConversation userConversation)
        {
            try
            {
                var oldUserConversation = _context.UserConversations.SingleOrDefault(x => x.Id == id);

                if (oldUserConversation == null)
                {
                    throw new NotFoundException(Errors.UserConversationNotFound);
                }

                //Update old message fields
                oldUserConversation.UpdateModifiedFields(oldUserConversation, ref _context);

                userConversation.UpdateDate = DateTime.Now;

                _context.Update(oldUserConversation);

                await _context.SaveChangesAsync();

                return(oldUserConversation.Id);
            }
            catch
            {
                throw;
            }
        }
Esempio n. 3
0
        public List <UserConversation> AddConversation(Conversation conversation, int creatorId, int withWhomId)
        {
            EntityEntry <Conversation> newlyAdded = DataContext.Conversations.Add(conversation);

            DataContext.SaveChanges();
            UserConversation forCreator     = new UserConversation();
            UserConversation forParticipant = new UserConversation();

            forCreator.Conversation     = newlyAdded.Entity;
            forParticipant.Conversation = newlyAdded.Entity;

            forCreator.WithWhomId = withWhomId;
            forCreator.UserId     = creatorId;

            forCreator.ConversationId     = conversation.ConversationId;
            forParticipant.ConversationId = conversation.ConversationId;

            forParticipant.WithWhomId = creatorId;
            forParticipant.UserId     = withWhomId;


            EntityEntry <UserConversation> uc  = DataContext.UserConversations.Add(forCreator);
            EntityEntry <UserConversation> uc2 = DataContext.UserConversations.Add(forParticipant);

            DataContext.SaveChanges();

            List <UserConversation> userConversations = new List <UserConversation>();

            userConversations.Add(uc.Entity);
            userConversations.Add(uc2.Entity);


            return(userConversations);
        }
 public IHttpActionResult CreateGroup(string name)
 {
     try
     {
         var loginUserId = User.Identity.GetUserId();
         var newCon      = new Conversation()
         {
             Id        = Guid.NewGuid().ToString(),
             CreatedBy = loginUserId,
             Name      = name,
             StartTime = DateTime.Now,
             IsGroup   = true
         };
         var savedCon = _context.Conversations.Add(newCon);
         var userCon  = new UserConversation()
         {
             ConversationId = savedCon.Id,
             UserId         = loginUserId,
             JoinedTime     = DateTime.Now
         };
         var savedUserCon = _context.UserConversations.Add(userCon);
         _context.SaveChanges();
         return(Json(savedCon.Id));
     }
     catch (Exception ex)
     {
         return(Json("error"));
     }
 }
Esempio n. 5
0
        public bool CreateNewConversation(User sender, User receiver)
        {
            try
            {
                var userConversationSender   = new UserConversation();
                var userConversationReceiver = new UserConversation();
                var userConversations        = new List <UserConversation>();
                userConversations.Add(userConversationSender);
                userConversations.Add(userConversationReceiver);


                var user = _context.Users.FirstOrDefault(u => u.Id == sender.Id);
                user?.UserConversations.Add(userConversationSender);
                _context.Users.FirstOrDefault(u => u.Id == receiver.Id)?.UserConversations.Add(userConversationReceiver);
                _context.Conversations.Add(new Conversation {
                    UserConversations = userConversations
                }
                                           );
                _context.SaveChanges();
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Sets the conversation identifier for the specified user.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="conversationId">The conversation identifier.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public async Task SetConversationIdAsync(string userId, string conversationId, CancellationToken cancellationToken)
        {
            using (var context = new MobileServiceContext())
            {
                var link = await context.UserConversations
                           .FirstOrDefaultAsync(l => l.UserId == userId, cancellationToken)
                           .ConfigureAwait(false);

                if (link == null)
                {
                    link = new UserConversation
                    {
                        Id             = Guid.NewGuid().ToString(),
                        UserId         = userId,
                        ConversationId = conversationId
                    };
                    context.UserConversations.Add(link);
                }
                else if (link.ConversationId == conversationId)
                {
                    return;
                }
                else
                {
                    link.ConversationId = conversationId;
                }

                await context
                .SaveChangesAsync(cancellationToken)
                .ConfigureAwait(false);
            }
        }
        public IHttpActionResult PutUserConversation(int id, UserConversationDto userConversationDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            UserConversation userConversation = Mapper.Map <UserConversationDto, UserConversation>(userConversationDto);

            if (id != userConversationDto.Id)
            {
                return(BadRequest());
            }

            db.Entry(userConversation).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserConversationExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Esempio n. 8
0
        public async Task <IActionResult> Edit(int id, [Bind("UserConversationId,UserId,ConversationId")] UserConversation userConversation)
        {
            if (id != userConversation.UserConversationId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(userConversation);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserConversationExists(userConversation.UserConversationId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ConversationId"] = new SelectList(_context.Conversations, "ConversationId", "ConversationId", userConversation.ConversationId);
            ViewData["UserId"]         = new SelectList(_context.Users, "Id", "Id", userConversation.UserId);
            return(View(userConversation));
        }
Esempio n. 9
0
        public async Task <Message> AddMessageAsync(UserConversation conversation, Message message)
        {
            await using var transaction = await _db.Database.BeginTransactionAsync();

            message.ConversationId       = conversation.ConversationId;
            message.Sent                 = DateTime.UtcNow;
            message.UserId               = _userService.UserId;
            conversation.LastReadMessage = message.Sent;
            _db.Add(message);
            await _db.SaveChangesAsync();

            _eventBus.Publish(new NewMessageEvent
            {
                MessageId      = message.Id, Users = GetAllOtherUsers(conversation), UserId = _userService.UserId,
                ConversationId = conversation.ConversationId, Text = message.Text
            });

            await transaction.CommitAsync();

            // foreach (int userId in GetAllOtherUsers(conversation)) TODO: DELETE
            // {
            //     _hub.Clients.Client(userId.ToString())?.NewMessage(message.UserId, message.Id, message.Text,
            //         conversation.ConversationId, conversation.User.FullName);
            // }

            return(message);
        }
Esempio n. 10
0
        private async void FriendListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var temp = (UserConversation)e.ClickedItem;

            ChosenConversation = new UserConversation()
            {
                displayName = temp.displayName,
                Id          = temp.Id,
                ifGroup     = temp.ifGroup,
                name        = new List <string>(),
                messages    = new List <Message>()
            };

            ChosenMessages.Clear();
            for (int i = 0; i < temp.name.Count; i++)
            {
                ChosenConversation.name.Add(temp.name[i]);
            }
            for (int i = 0; i < temp.messages.Count; i++)
            {
                ChosenConversation.messages.Add(temp.messages[i]);
                ChosenMessages.Add(new Message(temp.messages[i].userName, (string)temp.messages[i].message, temp.messages[i].isItself, temp.messages[i].dateTime));
            }
            await RefreshMessageListAsync();

            ConversationTitle.Text = ChosenConversation.displayName;
        }
Esempio n. 11
0
        public async Task <ManagerResponse <UserConversation> > SaveAsync(UserConversation conversation)
        {
            var current = await this.GetAsync(conversation?.UserId);

            // create or update
            var response = (ManagerResponse <UserConversation>)null;

            if (current == null)
            {
                response = await this.CreateAsync(conversation);
            }
            else
            {
                response = await this.UpdateAsync(conversation);
            }

            // we expect not to receive error up to this point
            if (response.HasError)
            {
                throw new Exception($"Unexpected error when saving User Conversation. Error Message: {string.Join(", ", response?.Errors)}");
            }
            else
            {
                return(response);
            }
        }
Esempio n. 12
0
        //public bool InitialMessages()
        //{
        //    Message message = new Message()
        //    {
        //        MessageText = "How Are You?",
        //        SentTime = System.DateTime.Now,
        //        ConversationID = 1,
        //        UserID = 1
        //    };
        //    _context.Messages.Add(message);
        //    _context.SaveChanges();
        //    message = new Message()
        //    {
        //        MessageText = "Are You Still Good?",
        //        SentTime = System.DateTime.Now.AddMinutes(1),
        //        ConversationID = 1,
        //        UserID = 1
        //    };
        //    _context.Messages.Add(message);
        //    _context.SaveChanges();
        //    message = new Message()
        //    {
        //        MessageText = "Im just fine",
        //        SentTime = System.DateTime.Now.AddMinutes(2),
        //        ConversationID = 1,
        //        UserID = 2
        //    };
        //    _context.Messages.Add(message);
        //    _context.SaveChanges();
        //    message = new Message()
        //    {
        //        MessageText = "How about you",
        //        SentTime = System.DateTime.Now.AddMinutes(1),
        //        ConversationID = 1,
        //        UserID = 2
        //    };
        //    _context.Messages.Add(message);
        //    _context.SaveChanges();
        //    return true;
        //}

        // CREATE NEW CONVERSATION
        public async Task <IActionResult> NewConversationAsync(int userId)
        {
            // Get UserID Of Sender
            var currentUserId = HttpContext.Session.GetInt32("userId");
            // Check If Receiver Existed
            var user = _context.Users.FirstOrDefault(u => u.ID == userId);

            if (user != null)
            {
                // Check If Conversation Already Existed
                var userConversationIdList = _context.UserConversations
                                             .Where(u => u.UserID == currentUserId).ToList();
                foreach (var i in userConversationIdList)
                {
                    var uConversation = _context.UserConversations
                                        .Include(u => u.Conversation)
                                        .Where(u => u.ConversationID == i.ConversationID).ToList();
                    foreach (var j in uConversation)
                    {
                        if (j.UserID == userId && j.Conversation.ConversationType == 0)
                        {
                            return(RedirectToAction("Home", "Messenger", new { id = j.ConversationID }));
                        }
                    }
                }
                // Create New Conversation
                Conversation conversation = new Conversation();
                DateTime     currentTime  = System.DateTime.Now;
                conversation.CreatedDate      = currentTime;
                conversation.ConversationType = 0;
                _context.Add(conversation);
                await _context.SaveChangesAsync();

                // Create New UserConversations
                // Get Conversation ID
                var conversationId = _context.Conversations
                                     .FirstOrDefault(c => c.CreatedDate == currentTime).ID;
                // Save User Conversations
                UserConversation uC1 = new UserConversation();
                uC1.ConversationID = conversationId;
                uC1.UserID         = (int)currentUserId;
                uC1.UserSeen       = 1;
                _context.Add(uC1);
                await _context.SaveChangesAsync();

                UserConversation uC2 = new UserConversation();
                uC2.ConversationID = conversationId;
                uC2.UserID         = userId;
                uC2.UserSeen       = 0;
                _context.Add(uC2);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Home", "Messenger", new { id = conversationId }));
            }
            return(NotFound());
        }
        public void UserConversationShouldHaveUserId()
        {
            var userConversation = new UserConversation
            {
                UserId         = null,
                ConversationId = 1,
            };

            Assert.Throws <InvalidOperationException>(
                () => this.dbContext.UserConversations.Add(userConversation));
        }
        public IHttpActionResult GetUserConversation(int id)
        {
            UserConversation userConversation = db.UserConversations.Find(id);

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

            return(Ok(Mapper.Map <UserConversation, UserConversationDto>(userConversation)));
        }
Esempio n. 15
0
 public static UserConversationViewModel ToViewModel(this UserConversation model)
 {
     return(new UserConversationViewModel
     {
         ConversationId = model.ConversationId,
         IsOwner = model.IsOwner,
         NotRead = model.NotRead,
         NotReadCount = model.NotReadCount,
         UserId = model.UserId
     });
 }
Esempio n. 16
0
 public async Task AddMessageAsync(UserConversation chosenConversation, string message_owner, string message_send, DateTime sendTime)
 {
     string  folderName = chosenConversation.displayName;
     Message message    = new Message()
     {
         message  = message_send,
         dateTime = sendTime,
         userName = message_owner
     };
     await _userService.AddMessageAsync(_userService.GetCurrentUserName(), folderName, message);
 }
Esempio n. 17
0
        public MainPage()
        {
            ConversationCollections = new ObservableCollection <UserConversation>();
            ChosenMessages          = new ObservableCollection <Message>();
            ChosenConversation      = new UserConversation();
            timer = new DispatcherTimer {
                Interval = new TimeSpan(0, 0, 3)
            };
            AddGroup_NameList = new List <string>();

            this.InitializeComponent();
        }
Esempio n. 18
0
        public async Task <IActionResult> ReadMessages(int id)
        {
            UserConversation conversation = _conversationService.GetUserConversation(id);

            if (conversation == null)
            {
                return(Forbid());
            }

            int res = await _conversationService.ReadAllMessagesAsync(conversation);

            return(Ok(res));
        }
Esempio n. 19
0
        public async Task <IActionResult> GetMessages(int id)
        {
            UserConversation conversation = _conversationService.GetUserConversation(id);

            if (conversation == null)
            {
                return(Forbid());
            }

            IEnumerable <Message> messages = await _conversationService.GetMessages(id);

            return(Ok(_mapper.Map <IEnumerable <MessageDto> >(messages.Reverse())));
        }
Esempio n. 20
0
        public async Task <IActionResult> AddMessage(int id, MessageDto message)
        {
            UserConversation conversation = _conversationService.GetUserConversation(id);

            if (conversation == null)
            {
                return(Forbid());
            }

            Message messageResult = await _conversationService.AddMessageAsync(conversation, new Message { Text = message.Text });

            return(Ok(_mapper.Map <MessageDto>(messageResult)));
        }
Esempio n. 21
0
        public async Task <int> ReadAllMessagesAsync(UserConversation userConversation)
        {
            var transaction = await _db.Database.BeginTransactionAsync(IsolationLevel.RepeatableRead);

            var count = await CountNewAsync(userConversation);

            userConversation.LastReadMessage = DateTime.UtcNow;
            await _db.SaveChangesAsync();

            await transaction.CommitAsync();

            return(count);
        }
Esempio n. 22
0
        public async Task <IActionResult> Create([Bind("UserConversationId,UserId,ConversationId")] UserConversation userConversation)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userConversation);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ConversationId"] = new SelectList(_context.Conversations, "ConversationId", "ConversationId", userConversation.ConversationId);
            ViewData["UserId"]         = new SelectList(_context.Users, "Id", "Id", userConversation.UserId);
            return(View(userConversation));
        }
        public IHttpActionResult DeleteUserConversation(int id)
        {
            UserConversation userConversation = db.UserConversations.Find(id);

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

            db.UserConversations.Remove(userConversation);
            db.SaveChanges();

            return(Ok(Mapper.Map <UserConversation, UserConversationDto>(userConversation)));
        }
Esempio n. 24
0
        /// <summary>
        /// Save user conversation
        /// </summary>
        /// <param name="userConversation"></param>
        /// <returns></returns>
        public async Task <int> Save(UserConversation userConversation)
        {
            try
            {
                _context.UserConversations.Add(userConversation);

                await _context.SaveChangesAsync();

                return(userConversation.Id);
            }
            catch
            {
                throw;
            }
        }
Esempio n. 25
0
        private async Task <ManagerResponse <UserConversation> > UpdateAsync(UserConversation conversation)
        {
            var request = _mapper.Map <UserConversationReqResp>(conversation);

            var response = await this._userConversationService.UpdateConversationAsync(request);

            if (response.HasError)                                                      //TODO: Check if this is correct
            {
                return(new ManagerResponse <UserConversation>(response?.ErrorMessage)); //TODO: wrapped up this into the Auto Mapper
            }
            else
            {
                return(new ManagerResponse <UserConversation>(_mapper.Map <UserConversation>(response?.Content)));
            }
        }
Esempio n. 26
0
        public IActionResult GetConversation(int id)
        {
            UserConversation conversation = _conversationService.GetUserConversation(id);

            if (conversation == null)
            {
                return(Forbid());
            }

            var result = _mapper.Map <ConversationDto>(conversation.Conversation);

            result.LastReadMessage = conversation.LastReadMessage;

            return(Ok(result));
        }
        public IHttpActionResult PostUserConversation(UserConversationDto userConversationDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            UserConversation userConversation = Mapper.Map <UserConversationDto, UserConversation>(userConversationDto);

            db.UserConversations.Add(userConversation);
            db.SaveChanges();

            Mapper.Map(userConversation, userConversationDto);

            return(CreatedAtRoute("DefaultApi", new { id = userConversationDto.Id }, userConversationDto));
        }
Esempio n. 28
0
        private async Task PopulateConversation()
        {
            var conversationOne = new Conversation
            {
                Id   = 1,
                Name = "aaa",
            };

            var conversationTwo = new Conversation
            {
                Id   = 2,
                Name = "bbb",
            };

            var conversationThree = new Conversation
            {
                Id   = 3,
                Name = "ccc",
            };

            var user = new ApplicationUser
            {
                Id             = "ddd",
                UserName       = "******",
                Email          = "fff",
                EmailConfirmed = true,
            };

            this.dbContext.Conversations.Add(conversationOne);
            this.dbContext.Conversations.Add(conversationTwo);
            this.dbContext.Conversations.Add(conversationThree);
            this.dbContext.Users.Add(user);
            await this.dbContext.SaveChangesAsync();

            var userConv = new UserConversation
            {
                UserId         = "ddd",
                ConversationId = 2,
            };

            this.dbContext.UserConversations.Add(userConv);
            await this.dbContext.SaveChangesAsync();
        }
        private async void SeedDataForMessagesTesting(MessengerContext context)
        {
            User testUser = context.Users.First();

            Conversation conversation = new Conversation
            {
                Name = "test conversation"
            };
            await context.Conversations.AddAsync(conversation);

            await context.SaveChangesAsync();

            UserConversation userConversation = new UserConversation
            {
                ConversationId = conversation.ConversationId,
                IsOwner        = true,
                UserId         = testUser.Id
            };
            await context.UserConversations.AddAsync(userConversation);

            await context.SaveChangesAsync();

            await context.Messages.AddRangeAsync(new Message[]
            {
                new Message
                {
                    Content      = "test message 1",
                    OwnerId      = testUser.Id,
                    DateSent     = DateTime.Now,
                    Conversation = conversation
                },
                new Message
                {
                    Content      = "test message 2",
                    OwnerId      = testUser.Id,
                    DateSent     = DateTime.Now.AddSeconds(5),
                    Conversation = conversation
                }
            });

            await context.SaveChangesAsync();
        }
Esempio n. 30
0
        public async Task <IActionResult> PutUserConversation([FromRoute] int id, [FromBody] UserConversation userConversation)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            if (id != userConversation.ConversationId)
            {
                return(this.BadRequest());
            }

            string userId = (await this.tokenService.GetCurrentUser(this.User)).Id;

            if (this.context.UserConversations.Any(x => x.ConversationId == id && x.UserId == userId && x.IsOwner) == false)
            {
                return(this.BadRequest("UserConversation not belongs to user"));
            }

            this.context.Entry(userConversation).State = EntityState.Modified;

            try
            {
                await this.context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException e)
            {
                if (!this.UserConversationExists(id))
                {
                    return(this.NotFound());
                }
                else
                {
                    this.logger.LogError("Unable to update UserConversation", e);

                    throw;
                }
            }

            return(this.NoContent());
        }