Exemplo n.º 1
0
        private async Task ThrowIfEncryptionForbiddenAsync(long senderId, long receiverId)
        {
            if (NodeSettings.Configs.Node.EncryptionType == EncryptionType.TotallyForbidden)
            {
                throw new EncryptionForbiddenException("Encryption is forbidden by the node settings.");
            }
            var receiver = await _loadUsersService.GetUserAsync(receiverId).ConfigureAwait(false);

            var sender = await _loadUsersService.GetUserAsync(senderId).ConfigureAwait(false);

            if (receiver == null || sender == null)
            {
                return;
            }
            if (receiver.NodeId != sender.NodeId)
            {
                var receiverNode = _connectionsService.GetNodeConnection(receiver.NodeId.Value);
                if (receiverNode == null)
                {
                    return;
                }
                if (receiverNode.Node.EncryptionType == EncryptionType.TotallyForbidden)
                {
                    throw new EncryptionForbiddenException("Encryption is forbidden by the receiver node settings.");
                }
            }
            else
            {
                if (NodeSettings.Configs.Node.EncryptionType == EncryptionType.NodeUsersForbidden)
                {
                    throw new EncryptionForbiddenException("Encryption is forbidden by the node settings.");
                }
            }
        }
Exemplo n.º 2
0
        public async Task DeleteUser()
        {
            var user = fillTestDbHelper.Users.FirstOrDefault();
            await deleteUsersService.DeleteUserAsync(user.Id);

            Assert.Null(await loadUsersService.GetUserAsync(user.Id));
        }
        public async Task HandleAsync()
        {
            NodeResponse response = default;

            try
            {
                TokenVm token = await tokensService.CheckTokenAsync(request.Token, NodeSettings.Configs.Node.Id).ConfigureAwait(false);

                UserVm user = await loadUsersService.GetUserAsync(token.UserId).ConfigureAwait(false);

                response = new UserTokensNodeResponse(request.RequestId, token, user);
            }
            catch (InvalidTokenException)
            {
                response = new ResultNodeResponse(request.RequestId, ErrorCode.InvalidAccessToken);
            }
            catch (TokensTimeoutException)
            {
                response = new ResultNodeResponse(request.RequestId, ErrorCode.AccessTokenTimeout);
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
                response = new ResultNodeResponse(request.RequestId, ErrorCode.UnknownError);
            }
            finally
            {
                NodeWebSocketCommunicationManager.SendResponse(response, current);
            }
        }
Exemplo n.º 4
0
        public async Task GetUser()
        {
            var expectedUser = fillTestDbHelper.Users.FirstOrDefault();
            var actualUser   = await loadUsersService.GetUserAsync(expectedUser.Id);

            Assert.Equal(expectedUser.Tag, actualUser.Tag);
        }
Exemplo n.º 5
0
        public async Task EditUserNode()
        {
            var user = fillTestDbHelper.Users.FirstOrDefault();
            await updateUsersService.EditUserNodeAsync(user.Id, 2);

            var actualUser = await loadUsersService.GetUserAsync(user.Id);

            Assert.Equal(2, actualUser.NodeId);
        }
Exemplo n.º 6
0
        public async Task <IActionResult> SendToEmail([FromForm] SendQRModel model)
        {
            Dictionary <string, string> errors = new Dictionary <string, string>();

            if (string.IsNullOrWhiteSpace(model.Email))
            {
                var user = await _loadUsersService.GetUserAsync(model.UserId).ConfigureAwait(false);

                if (user == null)
                {
                    errors.Add("userId", $"The user with the specified identifier was not found. ({nameof(model.UserId)} : {model.UserId})");
                }
                else
                {
                    string userEmail = user.Emails?.FirstOrDefault();
                    if (string.IsNullOrWhiteSpace(userEmail))
                    {
                        errors.Add("email", $"The email address is not specified in the request parameters and the user does not have an email address. ({nameof(model.UserId)} : {model.UserId})");
                    }
                    model.Email = userEmail;
                }
            }
            else
            {
                if (!ValidationHelper.IsEmailValid(model.Email))
                {
                    errors.Add("email", $"The specified value is not a valid email address. ({nameof(model.Email)} : {model.Email})");
                }
            }
            if (errors.Any())
            {
                return(new JsonResult(errors));
            }
            if (!string.IsNullOrWhiteSpace(model.UploadFileId))
            {
                await EmailHandler.SendEmailWithFileAsync(model.Email, await _fileStorage.GetStreamAsync(model.UploadFileId), model.UploadFileId, "QR-Code");

                await _fileStorage.RemoveAsync(model.UploadFileId);
            }
            return(Ok());
        }
        public async Task HandleAsync()
        {
            var user = await loadUsersService.GetUserAsync(notice.UserId).ConfigureAwait(false);

            if (user.NodeId != nodeConnection.Node.Id)
            {
                return;
            }

            if (notice.ConversationId != null && notice.ConversationType != null)
            {
                await deleteMessagesService.DeleteMessagesAsync(notice.ConversationId.Value, notice.ConversationType.Value, notice.UserId).ConfigureAwait(false);
            }
            else
            {
                await deleteMessagesService.DeleteMessagesAsync(notice.UserId).ConfigureAwait(false);
            }
        }
        public async Task <Response> CreateResponseAsync()
        {
            try
            {
                string fileAccessToken = RandomExtensions.NextString(64);
                var    token           = await qrCodesService.CreateTokenByQRCodeAsync(request.QR, request.DeviceTokenId, request.OSName, request.DeviceName, request.AppName).ConfigureAwait(false);

                var user = await loadUsersService.GetUserAsync(token.UserId).ConfigureAwait(false);

                clientConnection.UserId               = user.Id;
                clientConnection.FileAccessToken      = fileAccessToken;
                clientConnection.CurrentToken         = token;
                clientConnection.Confirmed            = user.Confirmed;
                clientConnection.CurrentDeviceTokenId = token.DeviceTokenId;
                noticeService.SendNewSessionNoticeAsync(clientConnection);
                return(new TokensResponse(request.RequestId, token, fileAccessToken, null, user));
            }
            catch (ObjectDoesNotExistsException ex)
            {
                return(new ResultResponse(request.RequestId, ex.Message, ObjectsLibrary.Enums.ErrorCode.ObjectDoesNotExists));
            }
        }
Exemplo n.º 9
0
        public async void NewMessageUpdateUserChatsAsync(MessageVm message)
        {
            try
            {
                UserVm senderInfo = await loadUsersService.GetUserAsync(message.SenderId.GetValueOrDefault()).ConfigureAwait(false);

                IEnumerable <long> usersId = await loadChatsService.GetChatUsersIdAsync(message.ConversationId.GetValueOrDefault()).ConfigureAwait(false);

                foreach (long userId in usersId)
                {
                    List <ConversationPreviewVm> cachedChats = (await GetUserChatsAsync(userId).ConfigureAwait(false))?.ToList();
                    if (cachedChats == null || cachedChats.All(opt => opt.ConversationId != message.ConversationId))
                    {
                        cachedChats = (await loadChatsService.GetUserChatPreviewAsync(userId, DateTime.UtcNow.ToUnixTime()).ConfigureAwait(false))?.ToList();
                        UpdateUserChats(userId, cachedChats);
                        continue;
                    }
                    ConversationPreviewVm updatedChat = cachedChats.FirstOrDefault(opt => opt.ConversationId == message.ConversationId);
                    if (updatedChat != null)
                    {
                        updatedChat.LastMessageSenderId   = message.SenderId;
                        updatedChat.LastMessageTime       = message.SendingTime;
                        updatedChat.LastMessageSenderName = senderInfo.NameFirst;
                        updatedChat.PreviewText           = message.Text;
                        updatedChat.LastMessageId         = message.GlobalId;
                        updatedChat.Read           = false;
                        updatedChat.AttachmentType = (AttachmentType?)message.Attachments?.FirstOrDefault()?.Type ?? null;
                        UpdateUserChats(userId, cachedChats);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
        public async void SendNewMessageNoticeToDialogUsers(IEnumerable <MessageDto> messages, ClientConnection senderClientConnection, long receiverId, bool saveMessageFlag = true)
        {
            try
            {
                long senderId = messages.FirstOrDefault().SenderId.GetValueOrDefault();
                var  dialogs  = await loadDialogsService.GetUsersDialogsAsync(senderId, receiverId);

                var    currentDialog = dialogs.FirstOrDefault(dial => dial.FirstUserId == receiverId);
                Notice senderNotice  = default;
                if (senderId != receiverId)
                {
                    var message = messages.FirstOrDefault(mess => mess.ConversationId != currentDialog.Id);
                    senderNotice = new NewMessageNotice(
                        MessageConverter.GetMessageVm(message, senderId),
                        MarkdownHelper.ContainsMarkdownUserCalling(message.Text, receiverId));
                }
                else
                {
                    var message = messages.FirstOrDefault();
                    senderNotice = new NewMessageNotice(
                        MessageConverter.GetMessageVm(message, senderId),
                        MarkdownHelper.ContainsMarkdownUserCalling(message.Text, receiverId));
                }
                var senderClients = connectionsService.GetUserClientConnections(messages.ElementAt(0).SenderId.GetValueOrDefault());
                if (senderClients != null)
                {
                    IEnumerable <ClientConnection> senderConnectionsExceptCurrent = senderClients.Where(connection => !Equals(senderClientConnection, connection));
                    await SendNoticeToClientsAsync(senderConnectionsExceptCurrent, senderNotice).ConfigureAwait(false);
                }
                if (messages.Count() == 2)
                {
                    var    message         = messages.FirstOrDefault(mess => mess.ConversationId == currentDialog.Id);
                    var    receiverClients = connectionsService.GetUserClientConnections(receiverId);
                    Notice receiverNotice  = new NewMessageNotice(
                        MessageConverter.GetMessageVm(message, receiverId),
                        MarkdownHelper.ContainsMarkdownUserCalling(message.Text, receiverId));
                    if (receiverClients != null && receiverClients.Any())
                    {
                        await SendNoticeToClientsAsync(receiverClients, receiverNotice).ConfigureAwait(false);
                    }
                    else
                    {
                        var receiver = await loadUsersService.GetUserAsync(receiverId).ConfigureAwait(false);

                        if (receiver.NodeId == NodeSettings.Configs.Node.Id && !saveMessageFlag)
                        {
                            await pendingMessagesService.AddUserPendingMessageAsync(receiverId, receiverNotice, message.GlobalId).ConfigureAwait(false);
                        }
                    }
                }
                DialogDto dialog = await loadDialogsService.GetDialogAsync(currentDialog.Id).ConfigureAwait(false);

                pushNotificationsService.SendMessageNotificationAsync(
                    messages.FirstOrDefault(opt => opt.ConversationId == currentDialog.Id),
                    new List <NotificationUser> {
                    new NotificationUser(dialog.FirstUserId, dialog.IsMuted)
                });
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }