Пример #1
0
 //запрос ключа друга
 private async void SendKeyRequest()
 {
     var message = new Message {
         Body = _requestKeyString
     };
     await _messageService.SendMessage(SelectedUser.Id, message);
 }
Пример #2
0
 //поиск файла с ключом среди сообщений - вызывать для всех "новых" сообщений
 private async Task GetKeyFileFromMessage(Message message)
 {
     if (message.Attachments == null)
     {
         return;
     }
     foreach (var attachment in message.Attachments)
     {
         var fileName = attachment.File?.FileName;
         if (fileName == null)
         {
             continue;
         }
         if (fileName == message.UserId + _publicFileName)
         {
             using (var client = new WebClient())
             {
                 try
                 {
                     await client.DownloadFileTaskAsync(attachment.File.Url, fileName);
                 }
                 catch (WebException)
                 {
                     MessageBox.Show("Ошибка загрузки файла с ключом. Попробуйте зайти в диалог еще раз.");
                     return;
                 }
                 SetFriendKey(SelectedUser.KeyExists, fileName);
                 File.Delete(fileName);
             }
         }
     }
 }
Пример #3
0
 public void createMessage(Message message)
 {
     int id = forum.Messages.Max(m => m.id);
     message.id = id + 1;
     forum.Messages.Add(message);
     forum.SaveChanges();
 }
Пример #4
0
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public void Update(Model.Message model)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("update Message set ");
            strSql.Append("[User]='" + model.User + "',");
            strSql.Append("UserMessage='" + model.UserMessage + "'");
            strSql.Append(" where ID=" + model.ID + " ");
            SQLHelper.ExecuteNonQuery(strSql.ToString());
        }
Пример #5
0
        //поиск запроса ключа и ответ на него - вызывать для всех "новых" сообщений
        private async Task <bool> FindKeyRequestAndReply(Message message)
        {
            if (message.Body == _requestKeyString && !message.Out)
            {
                await SendPublicKey(message.UserId, message.Id);

                return(true);
            }
            return(false);
        }
Пример #6
0
 public void TestGenerateTCPMessage()
 {
     User fromUser = new User("FromUser");
     User toUser = new User("ToUser");
     Message mess = new Message("This is the message");
     mess.FromUser = fromUser;
     mess.ToUser = toUser;
     String correctResult = "TCPMessage;FromUser;-1;ToUser;-1;This is the message";
     Assert.AreEqual(correctResult, Message.GenerateTCPMessage(mess));
 }
Пример #7
0
        private async void SendMessage()
        {
            if (!IsSendButtonEnabled)
            {
                return;
            }
            if (Message.Attachments != null && Message.Attachments.Any(a => a.IsNotCompleted))
            {
                var errorDialog = MessageBox.Show("Подождите окончания загрузки");
                return;
            }
            //добавляем полные имена файлов для расшифровки (#имя:ключ,имя:ключ)
            if (Message.Attachments != null && Message.Attachments.Any())
            {
                Message.Body += '#' + string.Join(",", Message.Attachments.Select(a => a.Document.FullName + ":" + a.EncryptedSymmetricKey).ToList());
            }

            try
            {
                IsMessageSending = true;

                if (string.IsNullOrEmpty(Message.Body) && (Message.Attachments == null || !Message.Attachments.Any()))
                {
                    return;
                }
                if (!string.IsNullOrEmpty(Message.Body))
                {
                    var simpleMessage = new Message
                    {
                        Body        = Message.Body,
                        UserId      = SelectedUser.Id,
                        Out         = true,
                        Attachments = Message.Attachments,
                        UnixTime    = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds,
                        IsNotRead   = true
                    };
                    var cryptedMessage = _cryptTool.MakingEnvelope(Message.Body);
                    Message.Body = cryptedMessage;

                    await _messageService.SendMessage(SelectedUser.Id, Message);

                    Message = new Message();
                    AddMessages(simpleMessage);
                }
            }
            catch (WebException)
            {
                ShowWebErrorMessage();
            }
            finally
            {
                IsMessageSending = false;
            }
        }
Пример #8
0
        protected void CreateMessageButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                User user = ForumAuth.Singleton.getUser(User.Identity.GetUserId());
                Message m = new Message() { thread = t, content = MessageContent.Text, user = user };

                ForumAuth.Singleton.saveMessage(m);

                Response.Redirect("~/ThreadMessages?id=" + t.id);
            }
        }
Пример #9
0
 public bool InsertMessage(Model.Message mess, out string msg)
 {
     if (dao_mess.insert(mess))
     {
         msg = "更改成功";
     }
     else
     {
         msg = "更改失败";
     }
     return(true);
 }
Пример #10
0
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public void Add(Model.Message model)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("insert into Message(");
            strSql.Append("[User],UserMessage");
            strSql.Append(")");
            strSql.Append(" values (");
            strSql.Append("'" + model.User + "',");
            strSql.Append("'" + model.UserMessage + "'");
            strSql.Append(")");
            SQLHelper.ExecuteNonQuery(strSql.ToString());
        }
Пример #11
0
        //отправить свой ключ другу - автоматом
        private async Task SendPublicKey(int userId, int messageToRemove)
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            var settings  = config.AppSettings.Settings;
            var confName  = "public_key_id";
            var docIdPath = settings[confName];

            var id = AuthorizeService.Instance.CurrentUserId;

            Document doc = null;

            if (docIdPath != null && docIdPath.Value != "")
            {
                //берем ключ с документов вк
                doc = (await _fileService.GetDocumentById(id + "_" + docIdPath.Value));
            }

            if (doc == null)
            {
                //есл в документах нет, загружаем
                if ((doc = await SavePublicKeyInVkDocs(Path.Combine(_keysPath, id + _publicFileName))) == null)
                {
                    return;
                }

                //сохраняем id, чтобы потом файл с вк вытащить
                if (docIdPath != null)
                {
                    settings.Remove(confName);
                }
                settings.Add(confName, doc.Id.ToString());
                config.Save(ConfigurationSaveMode.Modified);
            }
            var message = new Message
            {
                Attachments = new ObservableCollection <Attachment>
                {
                    new Attachment {
                        Document = doc, Type = "doc"
                    }
                },
                Body = "key"
            };
            await _messageService.SendMessage(userId, message);

            await _messageService.RemoveMessage(messageToRemove);
        }
Пример #12
0
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.Message GetModel(int ID)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("select   ");
            strSql.Append(" ID,[User],UserMessage,date ");
            strSql.Append(" from Message ");
            strSql.Append(" where ID=" + ID + " ");
            using (IDataReader dataReader = SQLHelper.ExecuteReader(strSql.ToString()))
            {
                if (dataReader.Read())
                {
                    model = ReaderBind(dataReader);
                }
            }
            return(model);
        }
Пример #13
0
        public MainViewModel()
        {
            _longPollServer.GotNewMessageEvent             += AddMessages;
            _longPollServer.MessageStateChangedToReadEvent += ChangeMessagesStateToRead;
            _longPollServer.UserBecameOnlineOrOfflineEvent += ChangeUserOnlineStatus;
            _longPollServer.ConnectToLongPollServer();

            Message = new Message();
            RenewDownloadView();

            SendMessageCommand      = new DelegateCommand(SendMessage);
            UploadFileCommand       = new DelegateCommand(OpenFileDialog);
            DownloadMessagesCommand = new DelegateCommand <ScrollChangedEventArgs>(DownloadMessages);
            DownloadFileCommand     = new DelegateCommand <Attachment>(DownloadFile);
            CancelFileUploadCommand = new DelegateCommand <Attachment>(CancelFileUpload);
            OpenDialogCommand       = new DelegateCommand <User>(OpenDialog);
            LogOutCommand           = new DelegateCommand(LogOut);
            SendKeyRequestCommand   = new DelegateCommand(SendKeyRequest);

            GetStartInfo();
            SaveKeysFileDialog();
        }
Пример #14
0
 private void TakeFileNamesFromBody(Message message)
 {
     if (message.Attachments != null && message.Attachments.Any())
     {
         //парсим имена файлов (текст#имя_файла1,имя_файла2)
         var probablyFiles            = message.Body.Split('#').Last();
         var cryptedfileNamesWithKeys = probablyFiles.Split(',').ToList();
         //todo условие может поломаться!!!
         if (!message.Body.Contains('#') || cryptedfileNamesWithKeys.Count != message.Attachments.Count ||
             (string.IsNullOrEmpty(cryptedfileNamesWithKeys[0]) && cryptedfileNamesWithKeys.Count == 1))
         {
             //сообщение не шифрованное или ошибка
             return;
         }
         message.Body = message.Body.Substring(0, message.Body.Length - probablyFiles.Length - 1);
         foreach (var attachment in message.Attachments) //восстанавливаем имена зашифрованных из message.body
         {
             var items = cryptedfileNamesWithKeys[message.Attachments.IndexOf(attachment)].Split(':');
             attachment.Document.FileName     = items[0];
             attachment.IsEncrypted           = true;
             attachment.EncryptedSymmetricKey = items[1];
         }
     }
 }
Пример #15
0
 /// <summary>
 /// 增加一条数据
 /// </summary>
 public void Add(Model.Message model)
 {
     dal.Add(model);
 }
Пример #16
0
 public bool InsertMessage(Model.Message message)
 {
     return(messageDAL.InsertMessage(message) == 1);
 }
Пример #17
0
 public void DeleteMessage(Model.Message message)
 {
     repoMessage.Delete(message);
 }
Пример #18
0
 public void AddMessage(Model.Message message)
 {
     repoMessage.Add(message);
 }
Пример #19
0
 public void deleteMessage(Message msg)
 {
     forum.Messages.Attach(msg);
     forum.Messages.Remove(msg);
     forum.SaveChanges();
 }
Пример #20
0
        private async void AddMessages(Message message)
        {
            if (message.Out && message.Body.StartsWith(_cryptTool._isCryptedFlag)) //не выводим свое отправленное зашифрованное сообщение - незачем
            {
                return;
            }

            if ((SelectedUser == null || message.UserId != SelectedUser.Id) && !message.Out)
            {
                var friend = FoundFriends.FirstOrDefault(f => f.Id == message.UserId);
                if (friend != null)
                {
                    if (friend.NumberOfNewMessages == null)
                    {
                        friend.NumberOfNewMessages = 1;
                    }
                    else
                    {
                        friend.NumberOfNewMessages++;
                    }
                    //UnreadDialogs.Add(friend);
                    FoundFriends.Remove(friend);
                    FoundFriends.Insert(0, friend);
                    FoundFriends = new List <User>(FoundFriends);
                }
                OnPropertyChanged("FoundFriends");
            }

            if (SelectedUser == null)
            {
                return;
            }


            var decryptedMessage = _cryptTool.SplitAndUnpackReceivedMessage(message.Body);

            message.Body = decryptedMessage;
            TakeFileNamesFromBody(message);
            if (message.Attachments != null && message.Attachments.Where(a => a.File == null).ToList().Count != 0)
            {
                message.HasUndefinedContent = true;
                message.Attachments         = new ObservableCollection <Attachment>(message.Attachments.Where(a => a.File != null));
            }


            if (message.UserId != SelectedUser.Id)
            {
                return;
            }
            message.User = message.Out ? AuthorizeService.Instance.CurrentUser : SelectedUser;

            if (!message.Out)
            {
                try
                {
                    message.IsNotRead = false;
                    _messageService.MarkMessagesAsRead(new List <int> {
                        message.Id
                    }, SelectedUser.Id);
                    await FindKeyRequestAndReply(message);
                    await GetKeyFileFromMessage(message);
                }
                catch (Exception)
                {
                    // ignored
                }
            }
            //todo переделать биндинг
            var messages = new List <Message>();

            messages.AddRange(Messages);
            messages.Add(message);
            Messages    = messages;
            ScrollToEnd = true;
        }
Пример #21
0
 public void TestParseTCPConnect()
 {
     User fromUser = new User("FromUser");
     User toUser = new User("ToUser");
     Message mess = new Message("Rename:123");
     mess.FromUser = fromUser;
     mess.ToUser = toUser;
     Assert.AreEqual("TCPNotify", Message.ParseTCPNotifyMessage(Message.GenerateTCPNotify(mess)).MessageType);
     Assert.AreEqual("FromUser", Message.ParseTCPNotifyMessage(Message.GenerateTCPNotify(mess)).FromUser.Name);
     Assert.AreEqual(-1, Message.ParseTCPNotifyMessage(Message.GenerateTCPNotify(mess)).FromUser.Id);
     Assert.AreEqual(null, Message.ParseTCPNotifyMessage(Message.GenerateTCPNotify(mess)).ToUser);
     Assert.AreEqual(("Rename:123"), Message.ParseTCPNotifyMessage(Message.GenerateTCPNotify(mess)).MessageContent);
 }
Пример #22
0
 public void TestParseTCPMessage()
 {
     User fromUser = new User("FromUser");
     User toUser = new User("ToUser");
     Message mess = new Message("This is the message");
     mess.FromUser = fromUser;
     mess.ToUser = toUser;
     Assert.AreEqual("TCPMessage", Message.ParseTCPNotifyMessage(Message.GenerateTCPMessage(mess)).MessageType);
     Assert.AreEqual("FromUser", Message.ParseTCPMessage(Message.GenerateTCPMessage(mess)).FromUser.Name);
     Assert.AreEqual(-1, Message.ParseTCPMessage(Message.GenerateTCPMessage(mess)).FromUser.Id);
     Assert.AreEqual("ToUser", Message.ParseTCPMessage(Message.GenerateTCPMessage(mess)).ToUser.Name);
     Assert.AreEqual(-1, Message.ParseTCPMessage(Message.GenerateTCPMessage(mess)).ToUser.Id);
     Assert.AreEqual(("This is the message"), Message.ParseTCPMessage(Message.GenerateTCPMessage(mess)).MessageContent);
 }
Пример #23
0
 public void select_info(Model.Message mess)
 {
     dao_mess.slt_info(mess);
 }
Пример #24
0
 /// <summary>
 /// 更新一条数据
 /// </summary>
 public void Update(Model.Message model)
 {
     dal.Update(model);
 }
Пример #25
0
 public void saveMessage(Message msg)
 {
     var existingPost = from m in forum.Messages where m.id == msg.id select m;
     if (existingPost.Any())
         forum.Entry(msg).State = System.Data.Entity.EntityState.Modified;
     else
     {
         msg.created = DateTime.Now;
         forum.Messages.Add(msg);
     }
     forum.SaveChanges();
 }