Exemple #1
0
        new public long?Insert(Conversation item)
        {
            long?insertedId = base.Insert(item);

            this.CloseConnection();
            if (insertedId == null)
            {
                return(null);
            }
            GroupConversation groupItem = (GroupConversation)item;
            string            sql       = "INSERT INTO Group_Conversations (Conversation_Id, Group_name) values (" + insertedId + ",'" + groupItem.ConversationName + "');";

            if (groupItem.MemberList != null)
            {
                foreach (Consumer member in groupItem.MemberList)
                {
                    sql += "GO INSERT INTO Group_Member_Map (Conversation_Id, Member_Id) values (" + insertedId + "," + member.Id + ");";
                }
            }
            string success = this.ExecuteSqlCeScalar(sql);

            if (success != null)
            {
                return(insertedId);
            }
            return(null);
        }
        public async Task <GroupConversation> CreateGroupConversation(GroupConversationDTO groupConversationDTO)
        {
            var groupConversation = new GroupConversation()
            {
                Name             = groupConversationDTO.GroupName,
                ConversationType = groupConversationDTO.ConversationType
            };

            await Context.GroupConversation
            .AddAsync(groupConversation);

            await Context.SaveChangesAsync();

            groupConversation = await Context.GroupConversation
                                .FirstOrDefaultAsync(gc => gc.Name == groupConversationDTO.GroupName);

            foreach (var groupMember in groupConversationDTO.GroupMembers)
            {
                var groupUser = new GroupUser()
                {
                    GroupId = groupConversation.Id,
                    UserId  = groupMember.Id
                };
                await Context.GroupUser
                .AddAsync(groupUser);
            }
            await Context.SaveChangesAsync();

            return(groupConversation);
        }
        public ActionResult <GroupMessageReadDto> Create([FromBody] GroupMessageCreateDto request)
        {
            if (_userRepository.Get(request.SenderId) == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "User doesn't exist."));
            }

            GroupConversation groupConversation = _groupConversationRepository.Get(request.GroupConversationId);

            if (groupConversation == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "GroupConversation doesn't exist."));
            }

            if (groupConversation.CreatorId != request.SenderId && !FormatHelper.CsvToListInt(groupConversation.ParticipantIds).Any(e => e == request.SenderId))
            {
                return(StatusCode(StatusCodes.Status403Forbidden, "Cannot create GroupMessage for GroupConversation you're not a part of."));
            }

            GroupMessage newEntity = _mapper.Map <GroupMessage>(request);

            newEntity.DateTime = DateTime.UtcNow;

            newEntity = _groupMessageRepository.Create(newEntity);

            return(StatusCode(StatusCodes.Status201Created, _mapper.Map <GroupMessageReadDto>(newEntity)));
        }
Exemple #4
0
        public ActionResult <GroupConversationReadDto> GetForUser(int id, int userId)
        {
            if (_userRepository.Get(userId) == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "User doesn't exist."));
            }

            GroupConversation found = _groupConversationRepository.Get(id);

            if (found == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "GroupConversation doesn't exist."));
            }

            List <int> formattedParticipantIds = FormatHelper.CsvToListInt(found.ParticipantIds);

            if (found.CreatorId != userId && !formattedParticipantIds.Any(e => e == userId))
            {
                return(StatusCode(StatusCodes.Status403Forbidden, "You can't access GroupConversations you're not a part of."));
            }

            GroupConversationReadDto result = _mapper.Map <GroupConversationReadDto>(found);

            result.ParticipantIdsList = formattedParticipantIds;

            return(StatusCode(StatusCodes.Status200OK, result));
        }
Exemple #5
0
        public GroupConversation Update(GroupConversation entity)
        {
            _context.Entry(entity).State = EntityState.Modified;

            _context.SaveChanges();

            return(entity);
        }
Exemple #6
0
        public GroupConversation Create(GroupConversation entity)
        {
            _context.GroupConversations.Add(entity);

            _context.SaveChanges();

            return(entity);
        }
Exemple #7
0
 private SearchedGroup(GroupConversation conversation, string currentUserId)
 {
     ImagePath              = conversation.GroupImagePath;
     Name                   = conversation.GroupName;
     HasPassword            = !string.IsNullOrEmpty(conversation.JoinPassword);
     OwnerId                = conversation.OwnerId;
     Id                     = conversation.Id;
     HasTimer               = conversation.MaxLiveSeconds < int.MaxValue;
     ConversationCreateTime = conversation.ConversationCreateTime;
 }
Exemple #8
0
        private void btnGroupCon_Click(object sender, EventArgs e)
        {
            var text        = tbGroupCon.Text;
            var destination = "/topic/" + text;

            _connection.SubscribeTo(destination);
            tbGroupCon.Text = "";
            var c = new GroupConversation(_connection.GetDestination(destination), text);

            _connection.AddConversation(c);
            OpenConversation(c);
        }
Exemple #9
0
 private SearchedGroup(GroupConversation conversation, string currentUserId)
 {
     UsersCount             = conversation.Users.Count();
     ImageKey               = conversation.GroupImageKey;
     Name                   = conversation.GroupName;
     HasPassword            = !string.IsNullOrEmpty(conversation.JoinPassword);
     OwnerId                = conversation.OwnerId;
     Id                     = conversation.Id;
     HasTimer               = conversation.MaxLiveSeconds < int.MaxValue;
     ConversationCreateTime = conversation.ConversationCreateTime;
     Joined                 = conversation.Users.Any(t => t.UserId == currentUserId);
 }
        public async Task <bool> DeleteConversationAsync(GroupConversation groupConversation)
        {
            var groupUsers = await Context.GroupUser
                             .Where(gu => gu.GroupId == groupConversation.Id)
                             .ToListAsync();

            Context.RemoveRange(groupUsers);
            Context.Remove(groupConversation);
            await Context.SaveChangesAsync();

            return(true);
        }
Exemple #11
0
        public GroupConversation Delete(int id)
        {
            GroupConversation entity = _context.GroupConversations.FirstOrDefault(e => e.Id == id);

            if (entity != null)
            {
                _context.GroupConversations.Remove(entity);
                _context.SaveChanges();
            }

            return(entity);
        }
Exemple #12
0
        public async Task <GroupConversation> CreateGroup(string groupName)
        {
            var newGroup = new GroupConversation
            {
                GroupName  = groupName,
                GroupImage = $"{_serviceLocation.CDN}/images/appdefaulticon.png"
            };

            this.GroupConversations.Add(newGroup);
            await this.SaveChangesAsync();

            return(newGroup);
        }
Exemple #13
0
        public ConversationDTO ParseConversation(GroupConversation conversation)
        {
            var conversationDTO = new ConversationDTO()
            {
                Id = conversation.Id,
                ConversationType  = conversation.ConversationType,
                ConversationPhoto = _defaultGroupPhotoName,
                ConversationName  = conversation.Name,
            };

            _photosUrlResolver.ResolveUrl(conversationDTO);

            return(conversationDTO);
        }
Exemple #14
0
        public async Task <GroupConversation> CreateGroup(string groupName, string creatorId, string joinPassword)
        {
            var newGroup = new GroupConversation
            {
                GroupName     = groupName,
                GroupImageKey = Convert.ToInt32(_configuration["GroupImageKey"]),
                AESKey        = Guid.NewGuid().ToString("N"),
                OwnerId       = creatorId,
                JoinPassword  = joinPassword ?? string.Empty
            };

            GroupConversations.Add(newGroup);
            await SaveChangesAsync();

            return(newGroup);
        }
Exemple #15
0
        public ConversationDTO ParseConversation(GroupConversation conversation, Message message, int userId)
        {
            var conversationDTO = new ConversationDTO()
            {
                Id = conversation.Id,
                ConversationType        = conversation.ConversationType,
                ConversationPhoto       = _defaultGroupPhotoName,
                ConversationLastMessage = (message.SenderId == userId) ? $"You: {message.MessageContent}" : message.MessageContent,
                ConversationName        = conversation.Name,
                LastMessageSendTime     = message.SendTime
            };

            _photosUrlResolver.ResolveUrl(conversationDTO);

            return(conversationDTO);
        }
Exemple #16
0
        public async Task <GroupConversation> CreateGroup(string groupName, string groupImagePath, string creatorId, string joinPassword)
        {
            var newGroup = new GroupConversation
            {
                GroupName      = groupName,
                GroupImagePath = groupImagePath,
                AESKey         = Guid.NewGuid().ToString("N"),
                OwnerId        = creatorId,
                JoinPassword   = joinPassword ?? string.Empty
            };
            await GroupConversations.AddAsync(newGroup);

            await SaveChangesAsync();

            return(newGroup);
        }
Exemple #17
0
        public async Task GroupJoinedEvent(KahlaUser receiver, GroupConversation createdConversation, Message latestMessage, int messageCount)
        {
            var token = await _appsContainer.AccessToken();

            var channel          = receiver.CurrentChannel;
            var groupJoinedEvent = new GroupJoinedEvent
            {
                CreatedConversation = createdConversation,
                LatestMessage       = latestMessage,
                MessageCount        = messageCount
            };

            if (channel > 0)
            {
                _cannonService.FireAsync <PushMessageService>(s => s.PushMessageAsync(token, channel, groupJoinedEvent));
            }
        }
Exemple #18
0
        public async Task GroupJoinedEvent(KahlaUser receiver, GroupConversation createdConversation, Message latestMessage, int messageCount)
        {
            var token = await _appsContainer.AccessToken();

            var channel          = receiver.CurrentChannel;
            var groupJoinedEvent = new GroupJoinedEvent
            {
                CreatedConversation = createdConversation,
                LatestMessage       = latestMessage,
                MessageCount        = messageCount
            };

            if (channel != -1)
            {
                await _stargatePushService.PushMessageAsync(token, channel, JsonConvert.SerializeObject(groupJoinedEvent), true);
            }
        }
Exemple #19
0
        public ActionResult <GroupConversationReadDto> Get(int id)
        {
            GroupConversation found = _groupConversationRepository.Get(id);

            if (found == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "GroupConversation doesn't exist."));
            }

            GroupConversationReadDto result = _mapper.Map <GroupConversationReadDto>(found);

            List <int> formattedParticipantIds = FormatHelper.CsvToListInt(found.ParticipantIds);

            result.ParticipantIdsList = formattedParticipantIds;

            return(StatusCode(StatusCodes.Status200OK, result));
        }
Exemple #20
0
        public async Task <IActionResult> JoinGroup([Required] string groupName, string joinPassword)
        {
            var user = await GetKahlaUser();

            if (!user.EmailConfirmed)
            {
                return(this.Protocol(ErrorType.Unauthorized, "You are not allowed to join groups without confirming your email!"));
            }
            GroupConversation group = null;

            lock (_obj)
            {
                group = _dbContext
                        .GroupConversations
                        .Include(t => t.Users)
                        .ThenInclude(t => t.User)
                        .SingleOrDefault(t => t.GroupName == groupName);
                if (group == null)
                {
                    return(this.Protocol(ErrorType.NotFound, $"We can not find a group with name: {groupName}!"));
                }
                if (group.HasPassword && group.JoinPassword != joinPassword?.Trim())
                {
                    return(this.Protocol(ErrorType.WrongKey, "The group requires password and your password was not correct!"));
                }

                var joined = group.Users.Any(t => t.UserId == user.Id);
                if (joined)
                {
                    return(this.Protocol(ErrorType.HasDoneAlready, $"You have already joined the group: {groupName}!"));
                }
                // All checked and able to join him.
                // Warning: Currently we do not have invitation system for invitation control is too complicated.
                var newRelationship = new UserGroupRelation
                {
                    UserId  = user.Id,
                    GroupId = group.Id
                };
                _dbContext.UserGroupRelations.Add(newRelationship);
                _dbContext.SaveChanges();
            }
            await group.ForEachUserAsync((eachUser, relation) => _pusher.NewMemberEvent(eachUser, user, group.Id), _userManager);

            return(this.Protocol(ErrorType.Success, $"You have successfully joint the group: {groupName}!"));
        }
Exemple #21
0
 private void SyncGroupToContacts(GroupConversation createdConversation, int messageCount, Message latestMessage)
 {
     _contacts.Add(new ContactInfo
     {
         AesKey           = createdConversation.AESKey,
         SomeoneAtMe      = false,
         UnReadAmount     = messageCount,
         ConversationId   = createdConversation.Id,
         Discriminator    = nameof(GroupConversation),
         DisplayImagePath = createdConversation.GroupImagePath,
         DisplayName      = createdConversation.GroupName,
         EnableInvisiable = false,
         LatestMessage    = latestMessage,
         Muted            = false,
         Online           = false,
         UserId           = createdConversation.OwnerId
     });
 }
Exemple #22
0
        public Conversation ParseConversation(ConversationDTO conversationDTO)
        {
            Conversation pc;

            if (conversationDTO.ConversationType == ConversationType.Private)
            {
                pc = new PrivateConversation()
                {
                    Id = conversationDTO.Id
                };
            }
            else
            {
                pc = new GroupConversation()
                {
                    Id = conversationDTO.Id
                };
            }

            return(pc);
        }
Exemple #23
0
        public ActionResult DeleteForUser(int id, int userId)
        {
            if (_userRepository.Get(userId) == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "User doesn't exist."));
            }

            GroupConversation found = _groupConversationRepository.Get(id);

            if (found == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "GroupConversation doesn't exist."));
            }

            List <int> formattedParticipantIds = FormatHelper.CsvToListInt(found.ParticipantIds);

            if (found.CreatorId != userId && !formattedParticipantIds.Any(e => e == userId))
            {
                return(StatusCode(StatusCodes.Status403Forbidden, "You can't access GroupConversations you're not a part of."));
            }

            if (found.CreatorId == userId)
            {
                _groupConversationRepository.Delete(id);
            }
            else
            {
                formattedParticipantIds.Remove(userId);

                found.ParticipantIds = FormatHelper.ListIntToCsv(formattedParticipantIds);

                _groupConversationRepository.Update(found);
            }

            return(StatusCode(StatusCodes.Status204NoContent));
        }
Exemple #24
0
        public ActionResult <GroupConversationReadDto> Create([FromBody] GroupConversationCreateDto request)
        {
            if (_userRepository.Get(request.CreatorId) == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "User doesn't exist."));
            }

            if (request.ParticipantIdsList.Any(e => _userRepository.Get(e) == null))
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "One or more Users don't exist."));
            }

            GroupConversation newEntity = _mapper.Map <GroupConversation>(request);

            newEntity.ParticipantIds = FormatHelper.ListIntToCsv(request.ParticipantIdsList);

            newEntity = _groupConversationRepository.Create(newEntity);

            GroupConversationReadDto result = _mapper.Map <GroupConversationReadDto>(newEntity);

            result.ParticipantIdsList = request.ParticipantIdsList;

            return(StatusCode(StatusCodes.Status201Created, result));
        }
Exemple #25
0
        private async Task ReceiveGroupAttachmentMessage(Message rMsg)
        {
            Conversation WasSelected = null;
            var          myDisp      = CoreApplication.MainView.CoreWindow.Dispatcher;
            await myDisp.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                if (recentMessageList.SelectedItem != null)
                {
                    WasSelected = recentMessageList.SelectedItem as Conversation;
                }
            });

            string grp_pp = "ms-appx:///Assets/default_group_profile_picture.png";

            var disp = CoreApplication.MainView.CoreWindow.Dispatcher;
            await disp.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                List <User> groupMessageUsers = new List <User>();
                for (int i = 1; i < receivedAttachmentGroupUsers.Length; i++)
                {
                    if (!ChatScreen.loggedInUser.Username.Equals(receivedAttachmentGroupUsers[i]))
                    {
                        User tempU = null;
                        foreach (User u in ChatScreen.availableUsers)
                        {
                            if (u.Username.Equals(receivedAttachmentGroupUsers[i]))
                            {
                                tempU = u;
                                break;
                            }
                        }
                        if (tempU != null)
                        {
                            groupMessageUsers.Add(tempU);
                        }
                        else
                        {
                            groupMessageUsers.Add(new User()
                            {
                                Username = receivedAttachmentGroupUsers[i]
                            });
                        }
                    }
                }

                foreach (Conversation c in ChatScreen.recentMessages)
                {
                    if (c is GroupConversation)
                    {
                        int count = 0;

                        foreach (User usr in groupMessageUsers)
                        {
                            foreach (User u in ((GroupConversation)c).GroupUsers)
                            {
                                if (usr.Username.Equals(u.Username))
                                {
                                    count++;
                                    break;
                                }
                            }
                        }

                        if ((count == ((GroupConversation)c).GroupUsers.Count) && (count == groupMessageUsers.Count))
                        {
                            c.Messages.Add(rMsg);
                            c.LastMessage = rMsg;
                            if (ChatScreen.recentMessages.IndexOf(c) != 0)
                            {
                                ChatScreen.recentMessages.Move(ChatScreen.recentMessages.IndexOf(c), 0);
                            }
                            messagePop.Play();
                            if (WasSelected != null)
                            {
                                recentMessageList.SelectedItem = WasSelected;
                            }
                            StoreConversations();
                            return;
                        }
                    }
                }

                GroupConversation newGroupConvo = new GroupConversation();

                string displayName = "";
                string userNames   = "";
                string emails      = "";
                foreach (User u in groupMessageUsers)
                {
                    displayName += u.Name;
                    userNames   += u.Username;
                    emails      += u.Email;

                    if (groupMessageUsers.Last() != u)
                    {
                        displayName += ", ";
                        userNames   += ", ";
                        emails      += ", ";
                    }

                    newGroupConvo.GroupUsers.Add(u);
                }
                User grpMsgUser = new User()
                {
                    Username = userNames, Email = emails, Name = displayName, ProfilePicture = grp_pp, IsGroupUser = true
                };
                newGroupConvo.MessageUser = grpMsgUser;
                newGroupConvo.Messages.Add(rMsg);
                newGroupConvo.LastMessage = rMsg;
                ChatScreen.recentMessages.Add(newGroupConvo);

                if (ChatScreen.recentMessages.IndexOf(newGroupConvo) != 0)
                {
                    ChatScreen.recentMessages.Move(ChatScreen.recentMessages.IndexOf(newGroupConvo), 0);
                }
                messagePop.Play();
                if (WasSelected != null)
                {
                    recentMessageList.SelectedItem = WasSelected;
                }
                StoreConversations();
            });
        }
        private void btnSend_click(object sender, RoutedEventArgs e)
        {
            GroupConversation conversation = new GroupConversation(_LyncClient);

            conversation.StartOrderConversation();
        }
        public static bool SyncUncachedConversations(List <Nuntias> nuntiasList)
        {
            Console.WriteLine("SyncUncachedConversations()");
            HashSet <long> conversationIdSet = new HashSet <long>();

            foreach (Nuntias nuntias in nuntiasList)
            {
                conversationIdSet.Add(nuntias.NativeConversationID);
            }
            List <long> unlistedConversationIdList = new List <long>();

            foreach (long conversationId in conversationIdSet)
            {
                bool?exists = ConversationRepository.Instance.ExistsConversation(conversationId);
                if (exists == false)
                {
                    unlistedConversationIdList.Add(conversationId);
                }
            }
            if (unlistedConversationIdList.Count == 0)
            {
                return(true);
            }
            List <JObject> conversationJsonList = null;

            ServerHub.WorkingInstance.ServerHubProxy.Invoke <List <JObject> >("GetConversations", unlistedConversationIdList).ContinueWith(task =>
            {
                if (!task.IsFaulted)
                {
                    conversationJsonList = task.Result;
                }
            }).Wait();
            if (conversationJsonList == null)
            {
                return(false);
            }
            foreach (JObject conversationJson in conversationJsonList)
            {
                long         id           = (long)conversationJson["id"];
                string       type         = (string)conversationJson["type"];
                Conversation conversation = null;
                if (type == "duet")
                {
                    Consumer member1 = ServerRequest.GetConsumer((long)conversationJson["member_id_1"]);
                    Consumer member2 = ServerRequest.GetConsumer((long)conversationJson["member_id_2"]);
                    if (member1 == null || member2 == null)
                    {
                        continue;
                    }
                    conversation = new DuetConversation(id, member1, member2);
                    DuetConversationRepository.Instance.Insert(conversation);
                }
                else if (type == "group")
                {
                    List <Consumer> memberList   = new List <Consumer>();
                    int             member_count = (int)conversationJson["member_counter"];
                    for (int i = 1; i <= member_count; i++)
                    {
                        memberList.Add(ServerRequest.GetConsumer((long)conversationJson["member_id_" + i]));
                    }
                    conversation = new GroupConversation(id, conversationJson["name"].ToString(), memberList);
                    GroupConversationRepository.Instance.Insert(conversation);
                }
            }
            return(true);
        }