Exemplo n.º 1
0
        // messages.createChat#419d9aee users:Vector<InputUser> title:string = messages.StatedMessage;
        public async Task <MessagesStatedMessage> CreateChat(string title, List <InputUser> usersToInvite)
        {
            var request = new CreateChatRequest(usersToInvite, title);

            await SendRpcRequest(request);

            return(request.statedMessage);
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Save([FromBody] CreateChatRequest request, CancellationToken cancellationToken)
        {
            await _chatService.CreateChat(new Save.Request
            {
                AdvertisementId = request.AdvertisementId
            }, cancellationToken);

            return(Ok());
        }
Exemplo n.º 3
0
        private void CreateChatHandler(string requestInJson)
        {
            CreateChatRequest request = JsonSerializer.Deserialize <CreateChatRequest>(requestInJson);

            try
            {
                User creator = server.UserRepository.GetByName(request.Sender);

                if (creator == null || creator.State != UserState.Authorized)
                {
                    throw new NedoGramException("Invalid user");
                }

                if (server.ChatRepository.GetChat(request.ChatName) != null)
                {
                    throw new NedoGramException("Chat with this name already exists");
                }

                aesEncryption.GenerateKey();
                byte[] key = aesEncryption.GetKey();

                IChat newChat = new Chat(creator, request.ChatName, key);
                newChat.AddUser(creator);

                server.UserRepository.UpdateState(creator.Name, UserState.InChat);

                server.ChatRepository.AddChat(newChat);
                creator.CurrentChat = newChat;

                var response = new CreateChatResponse
                {
                    ChatName  = newChat.Name,
                    Code      = StatusCode.Ok,
                    Key       = newChat.Key,
                    RequestId = request.Id,
                };

                SendMessageAesEncrypted(
                    response,
                    ClientAesKey);

                Console.WriteLine($"Chat created. ChatName - {newChat.Name}, Creator - {creator.Name}");
            }
            // todo: system exception should not be available to the client
            catch (Exception exception)
            {
                var errorResponse = new CreateChatResponse
                {
                    Code      = StatusCode.ServerError,
                    RequestId = request.Id,
                    Message   = exception.Message
                };

                SendMessageAesEncrypted(errorResponse, ClientAesKey);
                throw;
            }
        }
Exemplo n.º 4
0
        public async Task <ChatDto> CreateChat([FromBody] CreateChatRequest request)
        {
            var userId = HttpContext.GetCurrentUserId();

            var chatId = await _service.CreateChatAsync(request, userId);

            var chatDto = await _service.GetChatByIdAsync(chatId, userId);

            return(chatDto);
        }
Exemplo n.º 5
0
        public async Task <Messages_statedMessageConstructor> CreateChat(string title, List <int> userIdsToInvite)
        {
            var request = new CreateChatRequest(userIdsToInvite.Select(uid => new InputUserContactConstructor(uid)).ToList(), title);

            await _sender.Send(request);

            await _sender.Receive(request);

            return(request.message);
        }
Exemplo n.º 6
0
        public void Create()
        {
            var p = new CreateChatRequest
            {
                Name = Name
            };

            _manager.ConnectionInspector.Send(p);
            _manager.EventContent = null;
        }
        public async Task <IActionResult> Create([FromBody] CreateChatRequest request)
        {
            try
            {
                var thisUserId = ClaimsExtractor.GetUserIdClaim(User.Claims);

                var result = await mChatsService.CreateConversation(
                    request.ConversationName,
                    thisUserId,
                    request.DialogUserId,
                    request.ImageUrl,
                    request.IsGroup,
                    request.IsPublic,
                    request.IsSecure,
                    request.DeviceId);

                return(Ok(new ResponseApiModel <Chat>
                {
                    IsSuccessfull = true,
                    ErrorMessage = null,
                    Response = result
                }));
            }
            catch (InvalidDataException ex)
            {
                return(BadRequest(new ResponseApiModel <bool>
                {
                    IsSuccessfull = false,
                    ErrorMessage = ex.Message
                }));
            }
            catch (UnauthorizedAccessException ex)
            {
                return(StatusCode((int)HttpStatusCode.Forbidden, new ResponseApiModel <bool>
                {
                    IsSuccessfull = false,
                    ErrorMessage = ex.Message
                }));
            }
            catch (KeyNotFoundException ex)
            {
                return(NotFound(new ResponseApiModel <bool>
                {
                    IsSuccessfull = false,
                    ErrorMessage = ex.Message
                }));
            }
            catch (Exception)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, new ResponseApiModel <bool>
                {
                    IsSuccessfull = false
                }));
            }
        }
Exemplo n.º 8
0
        public IActionResult Create(CreateChatRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var userId = HttpContext.GetUserId();
            var result = _chatService.Create(userId, request.UserId);

            return(Ok(result));
        }
Exemplo n.º 9
0
        public ActionResult <GetChatResponce> Create(CreateChatRequest req)
        {
            var chat = service.CreateChat(req, ClientsUserId);

            if (chat == null)
            {
                return(Forbid());
            }
            foreach (ChatMember member in req.Members)
            {
                chatHubContext.Clients.Group(member.UserId).SendAsync("newChat", chat);
            }
            return(Ok());
        }
Exemplo n.º 10
0
        private void CreateChatRequestHandler()
        {
            Console.WriteLine(Environment.NewLine + "Write a chat name:");
            string newChatName = Console.ReadLine();

            var request = new CreateChatRequest(newChatName, UserName);

            responseHandlers.Add(request.Id, CreateChatResponseHandler);
            SendMessageAesEncrypted(request, serverKey);

            while (responseHandlers.ContainsKey(request.Id))
            {
            }
        }
Exemplo n.º 11
0
        public async Task <Guid> CreateChatAsync(CreateChatRequest request, Guid userId)
        {
            var chat = await _repository.CreateChatAsync(request.Name);

            foreach (var memberId in request.MemberIds)
            {
                await _repository.CreateChatMemberAsync(chat.Id, memberId);
            }

            // Add creator as a member
            await _repository.CreateChatMemberAsync(chat.Id, userId, ChatMemberStatus.Active, request.CreatorPublicKey);

            return(chat.Id);
        }
Exemplo n.º 12
0
 public void CreateChatTest()
 {
     try
     {
         CreateChatRequest request = new CreateChatRequest()
         {
             Email = "*****@*****.**"
         };
         var response = Client.CreateChat(request);
         Assert.IsNotNull(response);
     }
     catch (Exception ex)
     {
         Assert.Fail(ex.Message);
     }
 }
Exemplo n.º 13
0
        public IActionResult Create([FromForm] CreateChatRequest request)
        {
            if (request == null)
            {
                return(BadRequest("Unable to locate the body request"));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var chat = this.chatRepository.CreateChat(request.CallerIndentifiers);

            return(Created(new Uri($"/api/chat/get/{chat.Id}", UriKind.Relative), chat));
        }
Exemplo n.º 14
0
        public async Task <ActionResult <MainResponse> > CreateChat(CreateChatRequest request)
        {
            User user = HttpContext.GetUser();

            if (user == null || user.KeySession == null)
            {
                return(Unauthorized());
            }

            int[] keyIds = request.EncryptedPayload.Select(p => p.KeyId).ToArray();

            Chat chat = new Chat()
            {
                Id = RandomUtilities.GetCryptoRandomString(20),
                EncryptionChatDatas = new List <EncryptionChatData>(),
                Image           = "",
                LastMessageDate = DateTime.Now,
                LastMessageId   = null,
                Messages        = new List <Message>(),
            };

            _context.Chats.Add(chat);
            await _context.SaveChangesAsync();

            User[] users = await _context.Users.Where(p => keyIds.Contains(p.RSAKeyPair.Id)).ToArrayAsync();

            EncryptionChatData[] encryptionChatDatas = new EncryptionChatData[users.Length + 1];

            CreateChatEncryptedPayload encryptedPayload;

            for (int i = 0; i < users.Length; i++)
            {
                encryptedPayload       = request.EncryptedPayload.First(p => p.KeyId == users[i].RSAKeyPair.Id);
                encryptionChatDatas[i] = new EncryptionChatData()
                {
                    AESEncryptedKey    = new AESEncryptedData(),
                    Chat               = chat,
                    EncryptedTitle     = new AESEncryptedData(),
                    KeyTransferPayload = encryptedPayload.PayLoad,
                    RSAEncryptedKey    = encryptedPayload.EncryptedChatKey,
                    RSAKeyPair         = users[i].RSAKeyPair
                };
            }

            encryptionChatDatas[^ 1] = new EncryptionChatData()
        private async void createNewChat()
        {
            this.IsBusy      = true;
            this.BusyMessage = "Creazione chat in corso";

            HttpResponseMessage response = null;
            var request = new CreateChatRequest();

            request.CallerIdentifier   = CrossSettings.Current.GetValueOrDefault("CallerIdentifier", string.Empty);
            request.DeviceIdentifier   = CrossSettings.Current.GetValueOrDefault("DeviceIdentifier", string.Empty);
            request.CallerIndentifiers = new string[] { this.Contact.ID };

            string url = $"{base.BaseUrl}/Chat/Create";

            try
            {
                var formData = request.GetFormData();
                response = await base.Client.PostAsync(url, formData);
            }
            catch (Exception)
            {
            }

            if (response != null && response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject <CreateChatResponse>(content);
                this.ChatId = result.ID.ToString();
                var   filename = this.Contact.ID.ToString();
                IFile file     = await base.RootFolder.CreateFileAsync(filename, PCLStorage.CreationCollisionOption.ReplaceExisting);

                await file.WriteAllTextAsync(result.ID.ToString());
            }
            else
            {
                mvvm.Messenger.Default.Send <PromptMessage>(new PromptMessage("OOPPSS", "Qualcosa è andato storto!"));
                mvvm.Messenger.Default.Send <NavigateBackMessage>(new NavigateBackMessage());
            }

            this.BusyMessage = string.Empty;
            this.IsBusy      = false;
        }
Exemplo n.º 16
0
        public IHttpActionResult Create(CreateChatRequest request)
        {
            if (!HasValidCookie)
            {
                return(Unauthorized());
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            Chat chat = new Chat {
                AllowHtml = request.AllowHtml, Title = request.Title,
            };

            chat.UpdatedAt = System.DateTime.UtcNow;
            chat.UpdatedBy = CurrentUserId;
            chat.CreatedAt = System.DateTime.UtcNow;
            chat.CreatedBy = CurrentUserId;

            return(Ok(ToJsonString(DBContext.CreateChat(chat))));
        }
Exemplo n.º 17
0
        public GetChatResponce CreateChat(CreateChatRequest req, string userId)
        {
            var firstMessageSentAt = GetCurrentUnixTimestamp();

            Message message = new Message {
                Id           = req.FirstMessage.Id,
                Body         = req.FirstMessage.Body,
                AuthorUserId = userId,
                SentAt       = firstMessageSentAt
            };

            var messageDate = GetDateTimeFromUnixTimeStamp(message.SentAt);

            bool membersContainsClientsUserId = false;

            foreach (ChatMember member in req.Members)
            {
                if (member.UserId == userId)
                {
                    membersContainsClientsUserId = true;
                    continue;
                }
            }

            if (!membersContainsClientsUserId)
            {
                return(null);
            }

            List <ChatMember> members = req.Members.ToList();

            int authorsMemberIndex = members
                                     .FindIndex(m => m.UserId == userId);

            members[authorsMemberIndex].LastTimeOnChat = firstMessageSentAt;

            Chat chat = new Chat {
                Members      = members,
                UpdatedAt    = firstMessageSentAt,
                MessageLists = new List <MessageList> {
                    new MessageList {
                        Day      = messageDate.Day,
                        Month    = messageDate.Month,
                        Year     = messageDate.Year,
                        Messages = new List <Message> {
                            message
                        }
                    }
                },
                CreatedAt = firstMessageSentAt
            };

            Create(chat);

            GetChatResponce res = new GetChatResponce {
                Id        = chat.Id,
                CreatedAt = chat.CreatedAt,
                Members   = chat.Members,
                Messages  = chat.MessageLists.First().Messages,
                UpdatedAt = chat.UpdatedAt
            };

            return(res);
        }
Exemplo n.º 18
0
        public async Task <IActionResult> CreateChat(CreateChatRequest request)
        {
            using (var db = ArangoDatabase.CreateWithSetting())
            {
                var user = await db.Query <User>()
                           .Where(u => u.Key == HttpContext.User.Identity.Name)
                           .Select(u => u)
                           .FirstOrDefaultAsync();

                var group = await db.Query <Group>()
                            .Where(g => g.Key == request.ProjectId)
                            .Select(g => g)
                            .FirstOrDefaultAsync();

                if (user == null || group == null)
                {
                    return(BadRequest());
                }

                var rootGroup = await Database.GetRootGroup(request.ProjectId);

                var chat = new Chat
                {
                    Name      = request.Name,
                    Messages  = new List <Message>(),
                    IsGroup   = request.IsGroup,
                    ProjectId = rootGroup.Key
                };

                var createdChat = await db.InsertAsync <Chat>(chat);

                var usersInChatGraph = db.Graph("ChatsUsersGraph");


                var userToAdd = new ChatMembers
                {
                    Chat = createdChat.Id,
                    User = user.Id
                };

                await usersInChatGraph.InsertEdgeAsync <ChatMembers>(userToAdd);

                var notificationMessage =
                    $"{user.Username} te ha agregado al chat {chat.Name} en el proyecto {group.Name}";

                foreach (var userId in request.Members)
                {
                    var memberUser = Database.Query <User>().Where(u => u.Key == userId).Select(u => u).FirstOrDefault();
                    if (memberUser?.Key == HttpContext.User.Identity.Name)
                    {
                        continue;
                    }

                    userToAdd = new ChatMembers
                    {
                        Chat = createdChat.Id,
                        User = $"User/{userId}"
                    };

                    await usersInChatGraph.InsertEdgeAsync <ChatMembers>(userToAdd);


                    var notification = new Notification
                    {
                        Read     = false,
                        Message  = notificationMessage,
                        Priority = NotificationPriority.Medium,
                        Context  = $"project/{rootGroup.Key}/messages"
                    };
                    await NotificationHub.Clients
                    .Group($"User/{userId}")
                    .SendAsync("notificationReceived", notification);

                    memberUser?.Notifications.Add(notification);
                    await db.UpdateByIdAsync <User>(memberUser?.Id, memberUser);
                }

                return(Ok());
            }
        }