public AggregateMessagesActor(IEnumerable <IActorRef> actors, GetMessages request, IActorRef requester)
        {
            this.request         = request;
            this.requester       = requester;
            this.actorsToRespond = new HashSet <IActorRef>(actors);
            this.Self.Tell(new StartSearch());

            Context.SetReceiveTimeout(Timeout);
        }
Beispiel #2
0
        public async Task <MessagePage> Get(GetMessages request)
        {
            var messages = RavenSession.Query <Message>().Where(e => e.ChatId == request.ChatId).OrderByDescending(x => x.PostTime);
            var result   = new MessagePage();

            if (request.BeforePostTime != null)
            {
                messages = messages.Where(x => x.PostTime.UtcDateTime < request.BeforePostTime.Value.UtcDateTime);
            }
            var pageSize = request.PageSize ?? 10;

            var docs =
                await messages.Take(pageSize)
                .Include(x => x.UserId)
                .Include(s => s.Attachments)
                .ToListAsync();

            result.Messages = new List <MessageMold>();
            foreach (var doc in docs)
            {
                var user = await RavenSession.LoadAsync <User>(doc.UserId);

                var message = Mapper.Map <MessageMold>(doc);

                if (doc.Attachments != null)
                {
                    var attach = await RavenSession.LoadAsync <Attachment>(doc.Attachments);

                    message.Attachments = new List <AttachmentMold>();

                    foreach (var id in doc.Attachments)
                    {
                        if (attach.TryGetValue(id, out var attachment))
                        {
                            message.Attachments.Add(Mapper.Map <AttachmentMold>(attachment));
                        }
                        //TODO учесть в будущем показ потерянных файлов
                    }
                }

                if (user != null)
                {
                    message.UserNickName = string.IsNullOrWhiteSpace(user.DisplayName) ? user.Login : user.DisplayName;
                }
                result.Messages.Add(message);
            }
            return(result);
        }
Beispiel #3
0
        public async Task <IEnumerable <MessageDto> > HandleAsync(GetMessages query)
        {
            var user = await _userRepository.GetAsync(p => p.UserName == query.FromUserName);

            var myUser = await _userRepository.GetAsync(_userContext.Id);

            var result = await _messageRepository
                         .FindAndSortByAsync(x => (x.FromUserId == user.Id && x.ToUserId == _userContext.Id) ||
                                             (x.FromUserId == _userContext.Id && x.ToUserId == user.Id), x => x.CreatedAt);

            return(result.Select(p => new MessageDto
            {
                Id = p.Id,
                FromUserName = user.UserName,
                MyUserName = myUser.UserName,
                Content = p.Content,
                CreatedAt = p.CreatedAt
            }));
        }
Beispiel #4
0
 public MessagesService(GetMessages getMessages, AddOrUpdateMessage addOrUpdateMessage)
 {
     _getMessages        = getMessages;
     _addOrUpdateMessage = addOrUpdateMessage;
 }
        private bool ProcessMessageRequestEntrySecrets(
            GetMessages.ResponseParamsMessage messageItem, DeviceToDeviceMessages.IMessage message)
        {
            var messageContents = (DeviceToDeviceMessages.RequestEntrySecrets)message;
            
            var accountSettings = _model.ServerAccountSettings.Query().First();

            var entry = _model.Entries.Query().FirstOrDefault(r => r.Identifier == messageContents.EntryIdentifier);
            if (entry == null)
                return false;
            
            var linkedDeviceCryptoKeyId = accountSettings.LinkedDeviceCryptoKeyId;
            var linkedDeviceCryptoKey = _model.CryptoKeys.Query().First(r => r.Id == linkedDeviceCryptoKeyId);

            var entrySecrets = new Dictionary<string, string>();
            foreach (var secretIdentifier in messageContents.SecretIdentifiers)
            {
                var entrySecretsResult = _model.EntriesSharedSecrets.Query()
                    .FirstOrDefault(r => r.EntryId == entry.Id && r.SecretIdentifier == secretIdentifier);

                if (entrySecretsResult == null)
                    continue;

                var entrySecretData = _model.EntriesSharedSecretsData.Query().First(r => r.Id == entrySecretsResult.EntrySecretDataId);
                entrySecrets.Add(entrySecretsResult.SecretIdentifier, entrySecretData.Secret);
            }

            if (entrySecrets.Count != messageContents.SecretIdentifiers.Count)
            {
                // We don't appear to have all the requested secrets.
                return false;
            }

            var requestConfirmed = _controller.PromptSecretShareRequestSafe();

            var apiRequest = new SendLinkedDeviceMessage
            {
                //LinkIdentifier = link.Identifier,
                SecondsValidFor = 30
            };
            if (!requestConfirmed)
            {
                var deniedMessage = new DeviceToDeviceMessages.SendEntrySecrets
                {
                    OriginalMessageIdentifier = messageItem.Identifier,
                    RequestAccepted = false
                };
                apiRequest.SetMessage(deniedMessage, linkedDeviceCryptoKey.PublicKeyPem);
                apiRequest.GetResponse(GetApiClient());
                return true;
            }

            var acceptedMessage = new DeviceToDeviceMessages.SendEntrySecrets
            {
                OriginalMessageIdentifier = messageItem.Identifier,
                RequestAccepted = true,
                Secrets = entrySecrets
            };
            apiRequest.SetMessage(acceptedMessage, linkedDeviceCryptoKey.PublicKeyPem);
            apiRequest.GetResponse(GetApiClient());

            return true;
        }
        private bool ProcessMessageFromDevice(
            GetMessages.ResponseParamsMessage messageItem, DeviceToDeviceMessages.Envelope deviceMessage)
        {
            switch (deviceMessage.Type)
            {
                case DeviceToDeviceMessages.Types.NewSecret:
                    return ProcessMessageNewSecretShare(deviceMessage.Message);

                case DeviceToDeviceMessages.Types.RequestEntrySecrets:
                    return ProcessMessageRequestEntrySecrets(messageItem, deviceMessage.Message);

                case DeviceToDeviceMessages.Types.DeleteSecret:
                    return ProcessMessageDeleteSecret(deviceMessage.Message);

                default:
                    return false;
            }
        }
        /// <summary>
        /// Retrieve and process any outstanding messages from the server for the device.
        /// </summary>
        private void ProcessMessages()
        {
            var apiClient = GetApiClient();
            var accountSettings = _model.ServerAccountSettings.Query().First();

            GetMessagesLongpoll.ResponseParams longpollResponse;
            try
            {
                var longpollRequest = new GetMessagesLongpoll();
                _longpollInterrupt = new AutoResetEvent(false);
                longpollRequest.SetInteruptHandle(_longpollInterrupt);
                longpollResponse = longpollRequest.GetResponse(apiClient);
            }
            catch (RequestException)
            {
                return;
            }

            if (!longpollResponse.NewMessages)
                return;

            var getMessagesRequest = new GetMessages();
            GetMessages.ResponseParams messagesResponse;
            try
            {
                messagesResponse = getMessagesRequest.GetResponse(apiClient);
            }
            catch (RequestException)
            {
                return;
            }

            foreach (var messageItem in messagesResponse.Messages)
            {
                var processedSuccessfully = false;
                switch (messageItem.Type)
                {
                    case DeviceMessages.Types.ServerLoginRequest:
                        var loginRequestMessageContents = messageItem.GetContent<DeviceMessages.ServerLoginRequest>();
                        processedSuccessfully = ProcessMessageUserLoginRequest(loginRequestMessageContents);
                        break;

                    case DeviceMessages.Types.NewDatabase:
                        var newDatabaseMessageContents = messageItem.GetContent<DeviceMessages.NewDatabase>();
                        processedSuccessfully = ProcessMessageConfirmNewLink(newDatabaseMessageContents);
                        break;
                        
                    case DeviceMessages.Types.DeviceToDeviceMessage:
                        var messageContents = messageItem.GetContent<DeviceMessages.DeviceToDeviceMessage>();
                        var linkedDeviceCryptoKeyId = accountSettings.LinkedDeviceCryptoKeyId;
                        var linkedClientCryptoKey = _model.CryptoKeys.Query().First(r => r.Id == linkedDeviceCryptoKeyId);
                        if (!linkedClientCryptoKey.Trust)
                            break;

                        var message = getMessagesRequest.DecryptClientMessage(
                            messageContents.EncryptedMessage, linkedClientCryptoKey.PublicKeyPem);

                        processedSuccessfully = ProcessMessageFromDevice(messageItem, message);

                        break;

                    case DeviceMessages.Types.VerifyDeviceKeysRequest:
                        var verifyKeyMessageContents = messageItem.GetContent<DeviceMessages.VerifyDeviceKeysRequest>();
                        processedSuccessfully = ProcessMessageVerifyDeviceKeys(verifyKeyMessageContents);
                        break;

                    case DeviceMessages.Types.LinkedDeviceChange:
                        processedSuccessfully = ProcessMessageLinkedDeviceChange();
                        break;
                }

                var request = new SetMessageStatus
                {
                    DeviceMessageIdentifier = messageItem.Identifier,
                    ProcessedSuccess = processedSuccessfully
                };
                request.GetResponse(apiClient);
            }
        }
Beispiel #8
0
 public object Get(GetMessages request)
 {
     return(_repository.GetAll());
 }
        /// <summary>
        /// Retrieve and process any outstanding messages from the server for the device.
        /// </summary>
        private void ProcessMessages()
        {
            var apiClient       = GetApiClient();
            var accountSettings = _model.ServerAccountSettings.Query().First();

            GetMessagesLongpoll.ResponseParams longpollResponse;
            try
            {
                var longpollRequest = new GetMessagesLongpoll();
                _longpollInterrupt = new AutoResetEvent(false);
                longpollRequest.SetInteruptHandle(_longpollInterrupt);
                longpollResponse = longpollRequest.GetResponse(apiClient);
            }
            catch (RequestException)
            {
                return;
            }

            if (!longpollResponse.NewMessages)
            {
                return;
            }

            var getMessagesRequest = new GetMessages();

            GetMessages.ResponseParams messagesResponse;
            try
            {
                messagesResponse = getMessagesRequest.GetResponse(apiClient);
            }
            catch (RequestException)
            {
                return;
            }

            foreach (var messageItem in messagesResponse.Messages)
            {
                var processedSuccessfully = false;
                switch (messageItem.Type)
                {
                case DeviceMessages.Types.ServerLoginRequest:
                    var loginRequestMessageContents = messageItem.GetContent <DeviceMessages.ServerLoginRequest>();
                    processedSuccessfully = ProcessMessageUserLoginRequest(loginRequestMessageContents);
                    break;

                case DeviceMessages.Types.NewDatabase:
                    var newDatabaseMessageContents = messageItem.GetContent <DeviceMessages.NewDatabase>();
                    processedSuccessfully = ProcessMessageConfirmNewLink(newDatabaseMessageContents);
                    break;

                case DeviceMessages.Types.DeviceToDeviceMessage:
                    var messageContents         = messageItem.GetContent <DeviceMessages.DeviceToDeviceMessage>();
                    var linkedDeviceCryptoKeyId = accountSettings.LinkedDeviceCryptoKeyId;
                    var linkedClientCryptoKey   = _model.CryptoKeys.Query().First(r => r.Id == linkedDeviceCryptoKeyId);
                    if (!linkedClientCryptoKey.Trust)
                    {
                        break;
                    }

                    var message = getMessagesRequest.DecryptClientMessage(
                        messageContents.EncryptedMessage, linkedClientCryptoKey.PublicKeyPem);

                    processedSuccessfully = ProcessMessageFromDevice(messageItem, message);

                    break;

                case DeviceMessages.Types.VerifyDeviceKeysRequest:
                    var verifyKeyMessageContents = messageItem.GetContent <DeviceMessages.VerifyDeviceKeysRequest>();
                    processedSuccessfully = ProcessMessageVerifyDeviceKeys(verifyKeyMessageContents);
                    break;

                case DeviceMessages.Types.LinkedDeviceChange:
                    processedSuccessfully = ProcessMessageLinkedDeviceChange();
                    break;
                }

                var request = new SetMessageStatus
                {
                    DeviceMessageIdentifier = messageItem.Identifier,
                    ProcessedSuccess        = processedSuccessfully
                };
                request.GetResponse(apiClient);
            }
        }
Beispiel #10
0
        private void ProcessMessages()
        {
            var apiClient = GetApiClient();
            var serverAccount = Model.ServerAccounts.Get(_serverAccountId);

            CryptoKey linkedDeviceCryptoKey = null;
            if (serverAccount.LinkedDeviceCryptoKeyId != 0)
                linkedDeviceCryptoKey = Model.CryptoKeys.Get(serverAccount.LinkedDeviceCryptoKeyId);
            
            GetMessagesLongpoll.ResponseParams longpollResponse;
            try
            {
                var longpollRequest = new GetMessagesLongpoll();
                _longpollInterrupt = new AutoResetEvent(false);
                longpollRequest.SetInteruptHandle(_longpollInterrupt);
                longpollResponse = longpollRequest.GetResponse(apiClient);
            }
            catch (NetworkErrorException)
            {
                Logger.Info("Network error attempting to obtain images.");
                _requestErrors++;
                return;
            }
            catch (RequestException)
            {
                return;
            }

            _requestErrors = 0;

            if (!longpollResponse.NewMessages)
                return;

            var getMessagesRequest = new GetMessages();
            GetMessages.ResponseParams messagesResponse;
            try
            {
                messagesResponse = getMessagesRequest.GetResponse(apiClient);
            }
            catch (RequestException)
            {
                return;
            }
            
            foreach (var messageItem in messagesResponse.Messages)
            {
                if (_stopSyncLoop)
                    return;

                var processedSucessfully = false;

                if (messageItem.Type == DeviceMessages.Types.DeviceToDeviceMessage)
                {
                    if (linkedDeviceCryptoKey == null)
                        continue;

                    var messageContents = messageItem.GetContent<DeviceMessages.DeviceToDeviceMessage>();

                    //if (!string.IsNullOrEmpty(messageContents.LinkIdentifier))
                    //{
                        var message = getMessagesRequest.DecryptClientMessage(
                            messageContents.EncryptedMessage, linkedDeviceCryptoKey.PublicKeyPem);

                        switch (message.Type)
                        {
                            case DeviceToDeviceMessages.Types.SendEntrySecrets:
                                if (SendSecretShareMessageReceived == null)
                                    break;
                                var args = new SendEntrySecretsMessageReceivedEventArgs(
                                    (DeviceToDeviceMessages.SendEntrySecrets)message.Message);
                                SendSecretShareMessageReceived.Invoke(this, args);
                                processedSucessfully = args.MessageHandledSuccessfully;
                                break;
                    }
                    //}
                }
                else
                {
                    switch (messageItem.Type)
                    {
                        case DeviceMessages.Types.VerifyDeviceKeysResponse:
                            if (VerifyDeviceKeysResponseReceived == null)
                                break;
                            var args = new VerifyDeviceKeysResponseReceivedEventArgs(
                                messageItem.GetContent<DeviceMessages.VerifyDeviceKeysResponse>());
                            VerifyDeviceKeysResponseReceived.Invoke(this, args);
                            processedSucessfully = args.MessageHandledSuccessfully;
                            break;
                    }
                }
                
                var processedRequest = new SetMessageStatus
                {
                    DeviceMessageIdentifier = messageItem.Identifier,
                    ProcessedSuccess = processedSucessfully
                };
                processedRequest.GetResponse(apiClient);
            }
        }
Beispiel #11
0
 private void Handle(GetMessages msg)
 {
     _log.Info("Received message's Count: " + _messages.Count);
 }
 public async Task <IEnumerable <MessageDto> > GetMessages([FromRoute] GetMessages getMessages)
 {
     return(await _queryHandler.HandleAsync(getMessages));
 }
 public static Props GetProps(IEnumerable <IActorRef> actors, GetMessages request, IActorRef requester) =>
 Props.Create(() => new AggregateMessagesActor(actors, request, requester));
        public Task <GetMessagesResponse> GetMessagesAsync(IAgentContext context, MessageContext messageContext, GetMessages getMessages)
        {
            var response = new GetMessagesResponse
            {
                Messages = _storage[messageContext.Connection.Id].Select(x => x.Message).ToArray()
            };

            return(Task.FromResult(response));
        }
 public override GetMessagesResponse GetMessages(GetMessages GetMessages1)
 {
     throw new NotImplementedException();
 }
Beispiel #16
0
        public MainWindowViewModel()
        {
            Locator.CurrentMutable.RegisterConstant(this);
            User = new CurrentUserViewModel();
            Locator.CurrentMutable.RegisterConstant <ICurrentUser>(User);
            configuration = Locator.Current.GetService <IConfiguration>();
            settings      = configuration?.GetSection("ChatClientSettings")?.Get <ChatClientSettings>();

            var mapper = Locator.Current.GetService <IMapper>();

            if (settings == null)
            {
                settings = new ChatClientSettings();
            }

            if (settings.HostUrl.IsNullOrEmpty())
            {
                settings.HostUrl = "http://localhost:5000";
            }

            if (settings.AttachmentDefaultPath.IsNullOrEmpty())
            {
                settings.AttachmentDefaultPath = "\\Download";
            }

            serviceClient = new JsonServiceClient(settings.HostUrl);

            ProfileViewModel = new ProfileViewModel(serviceClient);
            Locator.CurrentMutable.RegisterConstant <IProfile>(ProfileViewModel);
            ProfileViewModel.IsOpenProfileEvent += () => WindowStates(WindowState.OpenProfile);

            AttachmentViewModel = new SendAttachmentsViewModel(serviceClient);

            SettingsViewModel = new SettingsViewModel(serviceClient);
            SettingsViewModel.OpenSettingsActiveEvent        += (e) => { WindowStates(WindowState.WindowSettings); };
            SettingsViewModel.TypeEnterEvent                 += (e) => { KeySendMessage = e; };
            SettingsViewModel.ContextMenuSettingsActiveEvent += (e) => { WindowStates(WindowState.HeaderMenuPopup); };
            SettingsViewModel.SetSelectedOnSettingsItemEvent += e => { TextHeaderMenuInSettings = SettingsViewModel.SettingsMenuActiveMain ? "Сообщения и чаты" : "Аудит входа"; };

            Width(false);
            User.UserName = settings.UserName;
            Tokens        = new TokenResult {
                AccessToken = settings.AccessToken, RefreshToken = settings.RefreshToken
            };

            Messages = new ObservableCollection <IMessagesContainerViewModel>();

            var bits            = Environment.Is64BitOperatingSystem ? "PC 64bit, " : "PC 32bit, ";
            var operatingSystem = bits + RuntimeInformation.OSDescription;

            string ipAddress = "";

            try
            {
                ipAddress = new WebClient().DownloadString("https://api.ipify.org");
            }
            catch (Exception e)
            {
                try
                {
                    IPHostEntry ipHost = Dns.GetHostEntry("localhost");
                    if (ipHost.AddressList.Length > 0)
                    {
                        ipAddress = ipHost.AddressList.Last().ToString();
                    }
                }
                catch (Exception exception) { }
            }
            var nameVersionClient = "SkillChat Avalonia Client 1.0";

            ConnectCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    _connection = new HubConnectionBuilder()
                                  .WithUrl(settings.HostUrl + "/ChatHub")
                                  .Build();

                    _hub = _connection.CreateHub <IChatHub>();
                    ProfileViewModel.SetChatHub(_hub);
                    AttachmentViewModel.SetChatHub(_hub);

                    if (Tokens == null || Tokens.AccessToken.IsNullOrEmpty())
                    {
                        Tokens = await serviceClient.PostAsync(new AuthViaPassword
                        {
                            Login = User.UserName, Password = User.Password
                        });
                        settings.AccessToken  = Tokens.AccessToken;
                        settings.RefreshToken = Tokens.RefreshToken;
                        settings.UserName     = User.UserName;
                        configuration.GetSection("ChatClientSettings").Set(settings);
                    }

                    serviceClient.BearerToken = Tokens.AccessToken;
                    this.ObservableForProperty(m => m.ExpireTime).Subscribe(change =>
                    {
                        if (change.Value != null)
                        {
                            //TODO запуск обновления токена
                        }
                    });

                    _connection.Subscribe <LogOn>(async data =>
                    {
                        if (data.Error)
                        {
                            IsSignedIn = false;
                            serviceClient.BearerToken = Tokens.RefreshToken;
                            try
                            {
                                Tokens = await serviceClient.PostAsync(new PostRefreshToken());
                                settings.AccessToken  = Tokens.AccessToken;
                                settings.RefreshToken = Tokens.RefreshToken;
                                configuration.GetSection("ChatClientSettings").Set(configuration);
                                await _hub.Login(Tokens.AccessToken, operatingSystem, ipAddress, nameVersionClient);
                            }
                            catch (Exception e)
                            {
                                Tokens = null;
                            }
                        }
                        else
                        {
                            IsSignedIn = true;
                            User.Id    = data.Id;
                            User.Login = data.UserLogin;
                            ExpireTime = data.ExpireTime;
                            var chats  = await serviceClient.GetAsync(new GetChatsList());
                            var chat   = chats.Chats.FirstOrDefault();
                            ChatId     = chat?.Id;
                            ChatName   = chat?.ChatName;
                            LoadMessageHistoryCommand.Execute(null);
                            //Получаем настройки
                            SettingsViewModel.ChatSettings = await serviceClient.GetAsync(new GetMySettings());
                            KeySendMessage = SettingsViewModel.ChatSettings.SendingMessageByEnterKey;
                        }
                    });

                    _connection.Subscribe <UpdateUserDisplayName>(async user =>
                    {
                        try
                        {
                            var updateMessages = Messages.Where(s => s is UserMessagesContainerViewModel);
                            foreach (var message in updateMessages)
                            {
                                foreach (var item in message.Messages.Where(s => s.UserId == user.Id))
                                {
                                    item.UserNickname = user.DisplayName;
                                }
                            }

                            ProfileViewModel.UpdateUserProfile(user.DisplayName, user.Id);
                        }
                        catch (Exception e)
                        {
                            SignOutCommand.Execute(null);
                        }
                    });

                    _connection.Subscribe <ReceiveMessage>(async data =>
                    {
                        var isMyMessage    = User.Id == data.UserId;
                        var hasAttachments = data.Attachments != null && data.Attachments.Count > 0;

                        MessageViewModel newMessage;

                        if (isMyMessage)
                        {
                            newMessage = hasAttachments ? new MyAttachmentViewModel() : new MyMessageViewModel();
                        }
                        else
                        {
                            newMessage = hasAttachments ? new UserAttachmentViewModel() : new UserMessageViewModel();
                        }

                        newMessage.Id           = data.Id;
                        newMessage.Text         = data.Message;
                        newMessage.PostTime     = data.PostTime;
                        newMessage.UserNickname = data.UserNickname ?? data.UserLogin;
                        newMessage.UserId       = data.UserId;

                        newMessage.Attachments = data.Attachments?
                                                 .Select(s =>
                        {
                            var attah = mapper?.Map <AttachmentMold>(s);
                            return(new AttachmentMessageViewModel(attah));
                        }).ToList();

                        var container = Messages.LastOrDefault();

                        if (isMyMessage)
                        {
                            if (!(container is MyMessagesContainerViewModel))
                            {
                                container = new MyMessagesContainerViewModel();
                                Messages.Add(container);
                            }
                        }
                        else
                        {
                            if (container is UserMessagesContainerViewModel)
                            {
                                var lastMessage = container.Messages.LastOrDefault();
                                if (lastMessage?.UserId != newMessage.UserId)
                                {
                                    container = new UserMessagesContainerViewModel();
                                    Messages.Add(container);
                                }
                            }
                            else
                            {
                                container = new UserMessagesContainerViewModel();
                                Messages.Add(container);
                            }

                            if (!windowIsFocused || SettingsViewModel.IsOpened)
                            {
                                Notify.NewMessage(newMessage.UserNickname, newMessage.Text.Replace("\r\n", " "));
                            }
                        }

                        container.Messages.Add(newMessage);
                        if (container.Messages.First() == newMessage)
                        {
                            newMessage.ShowNickname = true;
                        }

                        MessageReceived?.Invoke(new ReceivedMessageArgs(newMessage));
                    });

                    _connection.Closed += connectionOnClosed();
                    await _connection.StartAsync();
                    await _hub.Login(Tokens.AccessToken, operatingSystem, ipAddress, nameVersionClient);
                    //Messages.Add("Connection started");
                    IsShowingLoginPage    = false;
                    IsShowingRegisterPage = false;
                    ValidationError       = "";
                    IsConnected           = true;
                    User.Password         = "";
                }
                catch (Exception ex)
                {
                    //Изменение параеметров TextBox в случае ошибки
                    User.Error("неверный логин или пароль");
                    ErrorBe?.Invoke();
                    IsShowingLoginPage = _connection.State != HubConnectionState.Connected ? true : false;
                    //Messages.Add(ex.Message);
                }
            });

            if (Tokens.AccessToken.IsNullOrEmpty() == false)
            {
                ConnectCommand.Execute(null);
            }

            SendCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    await _hub.SendMessage(new HubMessage(ChatId, MessageText));
                    MessageText = null;
                }
                catch (Exception ex)
                {
                    SignOutCommand.Execute(null);
                }
            },
                                                         this.WhenAnyValue(m => m.IsConnected, m => m.MessageText,
                                                                           (b, m) => b == true && !string.IsNullOrEmpty(m)));

            LoadMessageHistoryCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    var first   = Messages.FirstOrDefault()?.Messages.FirstOrDefault();
                    var request = new GetMessages {
                        ChatId = ChatId, BeforePostTime = first?.PostTime
                    };

                    // Логика выбора сообщений по id чата
                    var result = await serviceClient.GetAsync(request);
                    foreach (var item in result.Messages)
                    {
                        var isMyMessage    = User.Id == item.UserId;
                        var hasAttachments = item.Attachments != null && item.Attachments.Count > 0;

                        MessageViewModel newMessage;

                        if (isMyMessage)
                        {
                            newMessage = hasAttachments ? new MyAttachmentViewModel() : new MyMessageViewModel();
                        }
                        else
                        {
                            newMessage = hasAttachments ? new UserAttachmentViewModel() : new UserMessageViewModel();
                        }

                        newMessage.Id           = item.Id;
                        newMessage.Text         = item.Text;
                        newMessage.PostTime     = item.PostTime;
                        newMessage.UserNickname = item.UserNickName;
                        newMessage.UserId       = item.UserId;

                        newMessage.Attachments = item.Attachments?.Select(s => new AttachmentMessageViewModel(s)).ToList();

                        var container = Messages.FirstOrDefault();

                        if (isMyMessage)
                        {
                            if (!(container is MyMessagesContainerViewModel))
                            {
                                container = new MyMessagesContainerViewModel();
                                Messages.Insert(0, container);
                            }
                        }
                        else
                        {
                            if (container is UserMessagesContainerViewModel)
                            {
                                var firstMessage = container.Messages.FirstOrDefault();
                                if (firstMessage?.UserId != newMessage.UserId)
                                {
                                    container = new UserMessagesContainerViewModel();
                                    Messages.Insert(0, container);
                                }
                            }
                            else
                            {
                                container = new UserMessagesContainerViewModel();
                                Messages.Insert(0, container);
                            }
                        }

                        container.Messages.Insert(0, newMessage);

                        var firstInBlock = container.Messages.First();
                        foreach (var message in container.Messages)
                        {
                            message.ShowNickname = firstInBlock == message;
                        }
                    }
                }
                catch (Exception e)
                {
                }
            });

            SignOutCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    Messages.Clear();
                    MessageText = null;
                    Tokens      = null;
                    IsSignedIn  = false;
                    IsConnected = false;
                    serviceClient.BearerToken = null;
                    if (_connection != null)
                    {
                        _connection.Closed -= connectionOnClosed();
                        await _connection.StopAsync();
                    }

                    _connection = null;
                    _hub        = null;

                    settings.AccessToken  = null;
                    settings.RefreshToken = null;
                    configuration.GetSection("ChatClientSettings").Set(settings);

                    WindowStates(WindowState.SignOut);
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    IsShowingLoginPage = true;
                }
            });
            IsShowingLoginPage = true;

            // Скрывает окно регистрации
            IsShowingRegisterPage = false;
            IsShowingLoginPage    = true;
            GoToRegisterCommand   = ReactiveCommand.Create <object>(_ =>
            {
                IsShowingRegisterPage = true;
                IsShowingLoginPage    = false;
                RegisterUser.Login    = User.UserName;
                User.Password         = "";
            });

            RegisterUser = new RegisterUserViewModel();
            RegisterUser.GoToLoginCommand = ReactiveCommand.Create <object>(_ =>
            {
                IsShowingRegisterPage = false;
                IsShowingLoginPage    = true;
                RegisterUser.Password = "";
                User.UserName         = RegisterUser.Login;
            });
            IsConnected     = false; //Скрывает окно чата
            RegisterCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                var request = new RegisterNewUser();
                try
                {
                    ValidationError = "";
                    if (string.IsNullOrWhiteSpace(RegisterUser.Login) ||
                        string.IsNullOrWhiteSpace(RegisterUser.Password))
                    {
                        throw new Exception("Не заполнены логин и/или пароль");
                    }
                    request.Login    = RegisterUser.Login;
                    request.Password = RegisterUser.Password;
                    request.UserName = RegisterUser.UserName;

                    Tokens = await serviceClient.PostAsync(request);

                    settings.AccessToken  = Tokens.AccessToken;
                    settings.RefreshToken = Tokens.RefreshToken;
                    settings.UserName     = RegisterUser.Login;
                    configuration.GetSection("ChatClientSettings").Set(settings);
                    ConnectCommand.Execute(null);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Ошибка регистрации {ex.Message}");
                    ValidationError = ex.Message;
                }
            });

            NotifyCommand = ReactiveCommand.Create <object>(obj =>
            {
                if (obj is IHaveIsActive win)
                {
                    windowIsFocused = win.IsActive;
                }
            });
            PointerPressedCommand = ReactiveCommand.Create <object>(obj =>
            {
                ProfileViewModel.ContextMenuClose();
                SettingsViewModel.CloseContextMenu();
            });

            ProfileViewModel.SignOutCommand            = SignOutCommand;
            ProfileViewModel.LoadMessageHistoryCommand = LoadMessageHistoryCommand;
        }
Beispiel #17
0
        public ActionResult Messages(int id)
        {
            GetMessages search = new GetMessages(_db, id, Requester());

            return(View(model: search.Execute()));
        }
Beispiel #18
0
        private static void Listen_client(object socket)
        {
            Socket connection_socket = socket as Socket;

            while (true)
            {
                try
                {
                    object clientMessage;
                    {
                        byte[] clientData = new byte[10000];
                        if (connection_socket.Receive(clientData) == 0)
                        {
                            continue;
                        }
                        clientMessage = Functions.Deserialize(clientData);
                        //ShowMessage("Получены некие данные", ConsoleColor.Red);
                    }
                    if (clientMessage is Message)
                    {
                        Message message = (clientMessage as Message);
                        if (message.WhetherRead)
                        {
                            int idObject = ManagerAccountsOnline.GetIdObjectMessageByHashCode(message);
                            if (idObject > -1)
                            {
                                ManagerAccountsOnline.Messages[idObject]
                                .WhetherRead = true;
                            }
                        }
                        else
                        {
                            ManagerAccountsOnline.SendMessage(message);
                        }
                    }
                    if (clientMessage is SendEmailRegistration)
                    {
                        SendEmailRegistration message = clientMessage as SendEmailRegistration;
                        SendMessageToEmail(message.Subject, message.Body, message.Email,
                                           message.Name + " " + message.Surname, connection_socket);
                    }
                    if (clientMessage is UserDisconnect)
                    {
                        UserDisconnect ud = (clientMessage as UserDisconnect);
                        ManagerAccountsOnline.DeleteUser(ud.ThisAccountInforamtion);
                        connection_socket.Shutdown(SocketShutdown.Both);
                        foreach (Socket sockeT in ManagerAccountsOnline.AccountsOnline.Values)
                        {
                            Functions.SerializeAndSend(ud, sockeT);
                        }
                        return;
                    }
                    if (clientMessage is SocketDisconnect)
                    {
                        connection_socket.Disconnect((clientMessage as SocketDisconnect).ReuseSocket);
                        connection_socket.Shutdown(SocketShutdown.Both);
                        return;
                    }
                    if (clientMessage is AccountInformation)
                    {
                        AccountInformation ai = clientMessage as AccountInformation;
                        if (SqlConnection.State == ConnectionState.Closed)
                        {
                            SqlConnection.Open();
                        }
                        int sex = 1;
                        if (!ai.ManWoman)
                        {
                            sex = 0;
                        }
                        string query = "INSERT INTO Accounts VALUES ('" + ai.FirstName + "','" + ai.LastName + "'," +
                                       sex + ", '" + ai.DateOfBirth.Year + "-" + ai.DateOfBirth.Month + "-" +
                                       ai.DateOfBirth.Day + "', '" + ai.Email + "','" + ai.HashPassword + "')";
                        SqlCommand command = new SqlCommand(query, SqlConnection);
                        command.ExecuteNonQuery();
                        command.Dispose();
                        ShowMessage("В базу данных был добавлен новый аккаунт", ConsoleColor.White);
                        SqlConnection.Close();
                    }
                    if (clientMessage is Authorization)
                    {
                        //Thread.Sleep(4000);
                        Authorization authorization = clientMessage as Authorization;
                        string        query         = "select * from Accounts where Email='" + authorization.Email +
                                                      "' and HashPassword='******'";
                        if (SqlConnection.State == ConnectionState.Closed)
                        {
                            SqlConnection.Open();
                        }
                        SqlCommand    command = new SqlCommand(query, SqlConnection);
                        SqlDataReader reader  = command.ExecuteReader();
                        reader.Read();
                        if (reader.HasRows)
                        {
                            bool manWoman = true;
                            if (reader.GetInt32(3) == 0)
                            {
                                manWoman = false;
                            }
                            AccountInformation ai = new AccountInformation(reader.GetInt32(0),
                                                                           reader.GetString(1), reader.GetString(2), manWoman, reader.GetDateTime(4),
                                                                           reader.GetString(5), reader.GetString(6));
                            Functions.SerializeAndSend(ai, connection_socket);
                            ManagerAccountsOnline.AddUser(ai, connection_socket);
                        }
                        else
                        {
                            AccountInformation accountInformation = new AccountInformation
                            {
                                IsNull = true
                            };
                            Functions.SerializeAndSend(accountInformation, connection_socket);
                        }
                        reader.Close();
                        SqlConnection.Close();
                    }
                    if (clientMessage is UniquenessEmail)
                    {
                        UniquenessEmail uniquenessEmail = (clientMessage as UniquenessEmail);
                        string          query           = "select Email from Accounts where Email='" + uniquenessEmail.Email + "'";
                        if (SqlConnection.State == ConnectionState.Closed)
                        {
                            SqlConnection.Open();
                        }
                        SqlCommand    command = new SqlCommand(query, SqlConnection);
                        SqlDataReader reader  = command.ExecuteReader();
                        reader.Read();
                        uniquenessEmail.YesNo = reader.HasRows;
                        reader.Close();
                        SqlConnection.Close();
                        Functions.SerializeAndSend(uniquenessEmail, connection_socket);
                    }
                    if (clientMessage is GetUsersOnline)
                    {
                        //ShowMessage("Пришёл запрос на получение списка пользователей", ConsoleColor.Red);
                        GetUsersOnline guo = (clientMessage as GetUsersOnline);
                        foreach (AccountInformation ar in ManagerAccountsOnline.AccountsOnline.Keys)
                        {
                            guo.AccountsInformation.Add(ar);
                        }
                        Functions.SerializeAndSend(guo, connection_socket);
                    }
                    if (clientMessage is GetAllUsers)
                    {
                        GetAllUsers gao   = (clientMessage as GetAllUsers);
                        string      query = "select * from Accounts";
                        if (SqlConnection.State == ConnectionState.Closed)
                        {
                            SqlConnection.Open();
                        }
                        SqlCommand    command = new SqlCommand(query, SqlConnection);
                        SqlDataReader reader  = command.ExecuteReader();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                bool manWoman = true;
                                if (reader.GetInt32(3) == 0)
                                {
                                    manWoman = false;
                                }
                                gao.AccountsInformation.Add(new AccountInformation(reader.GetInt32(0),
                                                                                   reader.GetString(1), reader.GetString(2), manWoman, reader.GetDateTime(4),
                                                                                   reader.GetString(5), reader.GetString(6)));
                            }
                        }
                        reader.Close();
                        SqlConnection.Close();
                        Functions.SerializeAndSend(gao, connection_socket);
                    }
                    if (clientMessage is GetMessages)
                    {
                        GetMessages gm    = clientMessage as GetMessages;
                        string      query = "select * from [Messages] where SenderAccountID=" + gm.SenderId +
                                            " and ReceiverAccountID=" + gm.RecieverId + " or SenderAccountID=" +
                                            gm.RecieverId + " and ReceiverAccountID=" + gm.SenderId + "  order by DateTimeSent";
                        if (SqlConnection.State == ConnectionState.Closed)
                        {
                            SqlConnection.Open();
                        }
                        SqlCommand    command = new SqlCommand(query, SqlConnection);
                        SqlDataReader reader  = command.ExecuteReader();
                        while (reader.Read())
                        {
                            Message message = new Message(reader.GetInt32(0), reader.GetInt32(1),
                                                          reader.GetInt32(2), reader.GetString(3), reader.GetDateTime(4), reader.GetBoolean(5));
                            gm.Messages.Add(message);
                        }
                        Functions.SerializeAndSend(gm, connection_socket);
                        reader.Close();
                        SqlConnection.Close();
                    }
                    if (clientMessage is RecoverPasswordMessage)
                    {
                        RecoverPasswordMessage message = (clientMessage as RecoverPasswordMessage);
                        string query = "select * from Accounts where Email='" + message.Email + "'";
                        if (SqlConnection.State == ConnectionState.Closed)
                        {
                            SqlConnection.Open();
                        }
                        SqlCommand    command = new SqlCommand(query, SqlConnection);
                        SqlDataReader reader  = command.ExecuteReader();
                        reader.Read();
                        if (reader.HasRows)
                        {
                            string randomCode = Functions.GetRandomCode();
                            SendMessageToEmail("Изменение пароля",
                                               "Для продолжения введите в программе этот код подтверждения: " + randomCode,
                                               message.Email, reader[1] + " " + reader[2], null);

                            Functions.SerializeAndSend(new GetCode(randomCode), connection_socket);
                        }
                        reader.Close();
                        SqlConnection.Close();
                    }
                    if (clientMessage is NewPassword)
                    {
                        NewPassword newPassword = (clientMessage as NewPassword);
                        string      query       = "update Accounts set HashPassword='******' where Email='" + newPassword.Email + "'";
                        if (SqlConnection.State == ConnectionState.Closed)
                        {
                            SqlConnection.Open();
                        }
                        SqlCommand command = new SqlCommand(query, SqlConnection);
                        try
                        {
                            command.ExecuteNonQuery();
                            command.Dispose();
                            Functions.SerializeAndSend(new MessageFromServer("Пароль был успешно изменён!"),
                                                       connection_socket);
                        }
                        catch (Exception exception)
                        {
                            ShowMessage(exception.Message, ConsoleColor.Red);
                        }
                    }
                }
                catch (SocketException ex)
                {
                    ShowMessage(ex.Message, ConsoleColor.Red);
                    connection_socket.Disconnect(false);
                    return;
                    //connection_socket.Shutdown(SocketShutdown.Both);
                }
                catch (Exception ex)
                {
                    ShowMessage(ex.ToString(), ConsoleColor.Red);
                    return;
                }
            }
        }