public async Task <bool> SendMessage(Message m, string dialogName, Activity context)
        {
            if (FirebaseController.instance.app == null)
            {
                FirebaseController.instance.initFireBaseAuth();
            }
            try
            {
                client = new Firebase.Database.FirebaseClient("https://easymessage-1fa08.firebaseio.com/chats/");

                var p = await client.Child(dialogName).PostAsync(JsonConvert.SerializeObject(m));

                if (p != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Newtonsoft.Json.JsonReaderException exc)
            {
                return(false);
            }
            catch (Exception ex)
            {
                Utils.MessageBox(ex.Message, context);
                return(false);
            }
        }
        public async Task <List <Message> > GetAllMessages(string dialogName, Activity context)
        {
            List <Message> messageList = new List <Message>();

            if (FirebaseController.instance.app == null)
            {
                FirebaseController.instance.initFireBaseAuth();
            }
            try
            {
                client = new Firebase.Database.FirebaseClient("https://easymessage-1fa08.firebaseio.com/chats/");
                var p = await client.Child(dialogName).OnceAsync <Message>();

                var enumerator = p.GetEnumerator();
                enumerator.MoveNext();
                while (enumerator.Current != null)
                {
                    Message temp = enumerator.Current.Object;
                    if (temp.flags[0] != MessageFlags.Key)
                    {
                        if (temp.flags[0] != MessageFlags.Encoded)
                        {
                            messageList.Add(temp);
                        }
                        else
                        {
                            if (temp.senderP != AccountsController.mainAccP.emailP)
                            {
                                CryptoProvider c = new CryptoProvider();
                                temp.contentP = c.Decrypt(temp.contentP, AccountsController.mainAccP.privateKeyRsaP);
                                messageList.Add(temp);
                            }
                            else
                            {
                                messageList.Add(temp);
                            }
                        }
                    }
                    enumerator.MoveNext();
                }
                return(messageList);
            }
            catch (Newtonsoft.Json.JsonReaderException exc)
            {
                return(messageList);
            }
            catch (Exception ex)
            {
                Utils.MessageBox(ex.Message, context);
                return(messageList);
            }
        }
        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            Message message = _messages[position];

            switch (GetItemViewType(position))
            {
            case VIEW_TYPE_MESSAGE_SENT:
                if (message.contentP != null)
                {
                    ((SentMessageHolder)holder).Time.Text = Convert.ToDateTime(message.timeP).ToUniversalTime().TimeOfDay.ToString();
                    if (message.flags != null && message.flags[0] == MessageFlags.Encoded)
                    {
                        MessagesController.instance.CreateTable();
                        ((SentMessageHolder)holder).Content.Text = MessagesController.instance.FindItemI(message).decodedP;
                    }
                    else
                    {
                        if (message.flagsP == 5)
                        {
                            MessagesController.instance.CreateTable();
                            ((SentMessageHolder)holder).Content.Text = MessagesController.instance.FindItemI(message).decodedP;
                        }
                        else
                        {
                            if (MessagesController.instance.FindItemI(message).decodedP != null)
                            {
                                ((SentMessageHolder)holder).Content.Text = MessagesController.instance.FindItemI(message).decodedP;
                            }
                            else
                            {
                                ((SentMessageHolder)holder).Content.Text = message.contentP;
                            }
                        }
                    }
                }
                break;

            case VIEW_TYPE_MESSAGE_RECEIVED:
                ((ReceivedMessageHolder)holder).Time.Text = Convert.ToDateTime(message.timeP).ToUniversalTime().TimeOfDay.ToString();
                if (message.flags != null && message.flags[0] == MessageFlags.Key)
                {
                    ((ReceivedMessageHolder)holder).Content.Text = "*содержимое скрыто*";
                }
                else
                {
                    ((ReceivedMessageHolder)holder).Content.Text = message.contentP;
                }
                ((ReceivedMessageHolder)holder).Sender.Text = message.senderP;
                break;
            }
        }
        /*public override Message this[int position]
         * {
         *  get
         *  {
         *      return _messages[position];
         *  }
         * }*/
        public override int GetItemViewType(int position)
        {
            Message message = _messages[position];

            if (message.senderP == AccountsController.mainAccP.emailP)
            {
                // If the current user is the sender of the message
                return(VIEW_TYPE_MESSAGE_SENT);
            }
            else
            {
                // If some other user sent the message
                return(VIEW_TYPE_MESSAGE_RECEIVED);
            }
        }
Ejemplo n.º 5
0
        public int UpdateItem(string dialogName, Message c)
        {
            dialogsList = connection.Table <MyDialog>().ToList();
            MyDialog temp = dialogsList.Find(x => x.dialogName == dialogName);

            if (temp != null)
            {
                temp.lastMessage = c;
                temp.contentP    = c.contentP;
                temp.receiverP   = c.receiverP;
                temp.senderP     = c.senderP;
                temp.timeP       = c.timeP;
                temp.messageFlag = Convert.ToInt32(c.flags[0]);
                temp.accessFlag  = Convert.ToInt32(c.access[0]);
                return(connection.Update(temp));
            }
            return(0);
        }
Ejemplo n.º 6
0
        protected async override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            try
            {
                //TextView name = FindViewById<TextView>(Resource.Id.nav_bar_name);
                //name.Text = AccountsController.mainAccP.loginP;
                //TextView ml = FindViewById<TextView>(Resource.Id.nav_bar_addr);
                //ml.Text = AccountsController.mainAccP.emailP;
                //CryptoProvider c = new CryptoProvider();
                //CryptoProvider.Encrupt("privet", AccountsController.mainAccP.openKeyRsaP,
                //AccountsController.mainAccP.privateKeyRsaP, c);

                connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
                networkInfo         = null;

                DialogsController.instance.CreateTable();
                oldDialogs = DialogsController.instance.GetItems().ToList();

                SetContentView(Resource.Layout.main_page);
                tb = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.tooolbarCommon);

                drawer = FindViewById <DrawerLayout>(Resource.Id.drawerLayout1);

                ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, Resource.String.openDrawer, Resource.String.closeDrawer);
                toggle.SyncState();

                navigation = FindViewById <NavigationView>(Resource.Id.navigationMain);
                navigation.SetNavigationItemSelectedListener(this);
                var      header = navigation.GetHeaderView(0);
                TextView name   = header.FindViewById <TextView>(Resource.Id.nav_bar_name);
                name.Text = AccountsController.mainAccP.loginP;
                TextView ml = header.FindViewById <TextView>(Resource.Id.nav_bar_addr);
                ml.Text = AccountsController.mainAccP.emailP;

                checkProgress  = FindViewById <ProgressBar>(Resource.Id.checkProgress);
                dialogs        = FindViewById <ListView>(Resource.Id.dialogsList);
                oldDialogsList = FindViewById <ListView>(Resource.Id.oldDialogsList);

                SetSupportActionBar(tb);
                Android.Support.V7.App.ActionBar abar = SupportActionBar;

                abar.SetHomeButtonEnabled(true);
                abar.SetDisplayShowTitleEnabled(true);
                abar.SetHomeAsUpIndicator(Resource.Drawable.menu);
                abar.SetDisplayHomeAsUpEnabled(true);

                check        = FindViewById <Button>(Resource.Id.check);
                check.Text   = "Проверить запросы";
                check.Click += async delegate
                {
                    networkInfo = connectivityManager.ActiveNetworkInfo;
                    if (networkInfo != null && networkInfo.IsConnected == true)
                    {
                        try
                        {
                            Task <List <MyDialog> > sizeTask = FirebaseController.instance.FindDialogs("Dialog " + AccountsController.mainAccP.emailP + "+", this);
                            checkProgress.Visibility = ViewStates.Visible;
                            check.Enabled            = false;
                            dialogs.Enabled          = false;
                            oldDialogsList.Enabled   = false;
                            dialogg = await sizeTask;
                            if (dialogg == null)
                            {
                                Utils.MessageBox("Нет новых запросов!", this);
                            }
                            else
                            {
                                refresh_dialogs();
                            }
                            checkProgress.Visibility = ViewStates.Invisible;
                            check.Enabled            = true;
                            dialogs.Enabled          = true;
                            oldDialogsList.Enabled   = true;
                        }
                        catch (Exception ex)
                        {
                            Utils.MessageBox("Невозможно загрузить запросы. Проверьте подключение к интернету", this);
                            checkProgress.Visibility = ViewStates.Invisible;
                            check.Enabled            = true;
                            dialogs.Enabled          = true;
                            oldDialogsList.Enabled   = true;
                        }
                    }
                    else
                    {
                        Utils.MessageBox("Невозможно загрузить запросы. Проверьте подключение к интернету", this);
                    }
                };


                dialogs.ItemClick += (sender, e) =>
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.SetTitle("Предупреждение");
                    builder.SetMessage("Разрешить начать диалог с данным пользователем?");
                    builder.SetCancelable(true);
                    builder.SetNegativeButton("Нет", async(s, ev) =>
                    {
                        Message c                = adapter[Convert.ToInt32(e.Id)];
                        MyDialog temp            = dialogg.Find(x => x.lastMessage == c);
                        Task <bool> denialTask   = FirebaseController.instance.SendDialogDenial(temp.dialogName, c.senderP);
                        bool answer              = await denialTask;
                        checkProgress.Visibility = ViewStates.Visible;
                        if (answer)
                        {
                            dialogg.Remove(temp);
                            messages.Remove(c);
                            refresh_dialogs();
                            Utils.MessageBox("Успешно!", this);
                        }
                        else
                        {
                            Utils.MessageBox("Ошибка! Повторите позже.", this);
                        }
                        checkProgress.Visibility = ViewStates.Invisible;
                    });
                    builder.SetPositiveButton("Да", async(s, ev) =>
                    {
                        Message c                = adapter[Convert.ToInt32(e.Id)];
                        MyDialog temp            = dialogg.Find(x => x.lastMessage == c);
                        Task <bool> responseTask = FirebaseController.instance.SendDialogResponse(temp.dialogName, c.senderP);
                        checkProgress.Visibility = ViewStates.Visible;
                        bool _answer             = await responseTask;
                        if (_answer)
                        {
                            dialogg.Remove(temp);
                            messages.Remove(c);
                            refresh_dialogs();
                            ContactsController.instance.CreateTable();
                            ContactsController.instance.SaveItem(new Contact {
                                contactAddressP = c.senderP, dialogNameP = temp.dialogName,
                                contactNameP    = "user name", contactRsaOpenKeyP = "no key"
                            }, false);
                            Task <int> firstIdtask = FirebaseController.instance.ReturnLastId(AccountsController.mainAccP.emailP, this);
                            int firstId            = await firstIdtask;
                            FirebaseController.instance.AddContact(c.senderP, AccountsController.mainAccP.emailP, firstId + 1, temp.dialogName);
                            Task <int> secondIdtask = FirebaseController.instance.ReturnLastId(c.senderP, this);
                            int secondId            = await secondIdtask;
                            FirebaseController.instance.AddContact(AccountsController.mainAccP.emailP, c.senderP, secondId + 1, temp.dialogName);
                            Utils.MessageBox("Успешно!", this);
                        }
                        else
                        {
                            Utils.MessageBox("Ошибка! Повторите позже.", this);
                        }
                        checkProgress.Visibility = ViewStates.Invisible;
                    });
                    Dialog dialog = builder.Create();
                    dialog.Show();
                    return;
                };

                checkProgress.Visibility = ViewStates.Visible;
                await fillOld();

                if (oldDialogs != null)
                {
                    /**/
                    oldDialogs = oldDialogs.OrderByDescending(x => x.accessFlag).ToList().OrderByDescending(x => Convert.ToDateTime(x.timeP)).ToList();
                    adapterOld = new OldDialogItemAdapter(oldDialogs);
                }
                else
                {
                    /**/
                    oldDialogs = oldDialogs.OrderByDescending(x => x.accessFlag).ToList().OrderByDescending(x => Convert.ToDateTime(x.timeP)).ToList();
                    oldDialogs = new List <MyDialog>();
                    adapterOld = new OldDialogItemAdapter(oldDialogs);
                }
                oldDialogsList.Adapter   = adapterOld;
                checkProgress.Visibility = ViewStates.Invisible;

                oldDialogsList.ItemClick += (sender, e) =>
                {
                    Intent i = new Intent(this, typeof(DialogActivity));
                    i.SetFlags(ActivityFlags.NoAnimation);
                    MyDialog temp = adapterOld[Convert.ToInt32(e.Id)];
                    DialogsController.currDialP = temp;
                    i.PutExtra("dialogName", temp.dialogName);
                    i.PutExtra("receiver",
                               temp.receiverP == AccountsController.mainAccP.emailP ? temp.senderP : temp.receiverP); //изменил (убрал .lastMessage) возможно поэтому что-то сломалось
                    i.PutExtra("flag", 1);
                    StartActivity(i);
                };
            }
            catch (Exception ex)
            {
                //Utils.MessageBox(ex.Message, this);
            }
        }
Ejemplo n.º 7
0
        public void OnDataChange(DataSnapshot snapshot)
        {
            try
            {
                IEnumerable <DataSnapshot> items = snapshot.Children?.ToEnumerable <DataSnapshot>();
                List <DataSnapshot>        t     = items.ToList();
                var a = t.Last().Children.ToEnumerable <DataSnapshot>().ToList();

                var access             = a[0].Child("0").Value;
                List <AccessFlags> acs = new List <AccessFlags>();
                acs.Add((AccessFlags)Convert.ToInt32(access.ToString()));

                var flag = a[2].Child("0").Value;
                List <MessageFlags> fls = new List <MessageFlags>();
                fls.Add((MessageFlags)Convert.ToInt32(flag.ToString()));

                Message m = new Message
                {
                    contentP  = a[1].Value.ToString(),
                    flags     = fls,
                    access    = acs,
                    receiverP = a[3].Value.ToString(),
                    senderP   = a[4].Value.ToString(),
                    timeP     = a[5].Value.ToString(),
                };

                MyDialog md = oldDialogs.Find(x => x.contentP == m.contentP && x.timeP == m.timeP);
                if (md == null)
                {
                    string sender   = m.senderP.Replace(".", ",");
                    string receiver = m.receiverP.Replace(".", ",");
                    string s1       = "Dialog " + sender + "+" + receiver;
                    string s2       = "Dialog " + receiver + "+" + sender;
                    int    temp     = oldDialogs.FindIndex(x => x.dialogName == s1);
                    if (temp < 0)
                    {
                        temp = oldDialogs.FindIndex(x => x.dialogName == s2);
                        if (temp < 0)
                        {
                        }
                        else
                        {
                            m.dialogName = oldDialogs[temp].dialogName;
                            oldDialogs[temp].lastMessage = m;
                            oldDialogs[temp].accessFlag  = Convert.ToInt32(m.access[0]);
                            oldDialogs[temp].contentP    = m.contentP;
                            oldDialogs[temp].messageFlag = Convert.ToInt32(m.flags[0]);
                            oldDialogs[temp].receiverP   = m.receiverP;
                            oldDialogs[temp].senderP     = m.senderP;
                            oldDialogs[temp].timeP       = m.timeP;

                            DialogsController.instance.CreateTable();
                            DialogsController.instance.UpdateItem(oldDialogs[temp].dialogName, oldDialogs[temp].lastMessage);

                            /**/
                            oldDialogs             = oldDialogs.OrderByDescending(x => x.accessFlag).ToList().OrderByDescending(x => Convert.ToDateTime(x.timeP)).ToList();
                            adapterOld             = new OldDialogItemAdapter(oldDialogs, true);
                            oldDialogsList.Adapter = adapterOld;
                        }
                    }
                    else
                    {
                        m.dialogName = oldDialogs[temp].dialogName;
                        oldDialogs[temp].lastMessage = m;
                        oldDialogs[temp].accessFlag  = Convert.ToInt32(m.access[0]);
                        oldDialogs[temp].contentP    = m.contentP;
                        oldDialogs[temp].messageFlag = Convert.ToInt32(m.flags[0]);
                        oldDialogs[temp].receiverP   = m.receiverP;
                        oldDialogs[temp].senderP     = m.senderP;
                        oldDialogs[temp].timeP       = m.timeP;

                        DialogsController.instance.CreateTable();
                        DialogsController.instance.UpdateItem(oldDialogs[temp].dialogName, oldDialogs[temp].lastMessage);

                        /**/
                        oldDialogs             = oldDialogs.OrderByDescending(x => x.accessFlag).ToList().OrderByDescending(x => Convert.ToDateTime(x.timeP)).ToList();
                        adapterOld             = new OldDialogItemAdapter(oldDialogs, true);
                        oldDialogsList.Adapter = adapterOld;
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.MessageBox("Сетевая ошибка!", this);
            }
        }
Ejemplo n.º 8
0
        protected override void OnResume()
        {
            base.OnResume();
            if (DialogsController.currDialP != null)
            {
                DialogsController.instance.CreateTable();
                oldDialogs = DialogsController.instance.GetItems().ToList();
                /**/
                oldDialogs                  = oldDialogs.OrderByDescending(x => x.accessFlag).ToList().OrderByDescending(x => Convert.ToDateTime(x.timeP)).ToList();
                adapterOld                  = new OldDialogItemAdapter(oldDialogs);
                oldDialogsList.Adapter      = adapterOld;
                DialogsController.currDialP = null;
            }
        }

        private async Task <bool> fillOld()
        {
            networkInfo = connectivityManager.ActiveNetworkInfo;
            if (networkInfo != null && networkInfo.IsConnected == true)
            {
                try
                {
                    Task <List <MyDialog> > oldTask = FirebaseController.instance.FindOldDialogs(AccountsController.mainAccP.emailP, this);
                    oldDialogs = await oldTask;

                    if (oldDialogs != null)
                    {
                        DialogsController.instance.CreateTable();
                        foreach (var d in oldDialogs)
                        {
                            d.FillFields();
                            DialogsController.instance.SaveItem(d);
                        }

                        var newDialos = oldDialogs.FindAll(x => Convert.ToInt32(x.lastMessage.flags[0]) == 6);
                        if (newDialos != null && newDialos.Count > 0)
                        {
                            key_exchange(newDialos);
                        }
                    }

                    if (FirebaseController.instance.app == null)
                    {
                        FirebaseController.instance.initFireBaseAuth();
                    }
                    FirebaseDatabase databaseInstance = FirebaseDatabase.GetInstance(FirebaseController.instance.app);
                    var userNode = databaseInstance.GetReference("chats");
                    foreach (var dialog in oldDialogs)
                    {
                        DatabaseReference u = userNode.Child(dialog.dialogName);
                        u.AddValueEventListener(this);
                    }
                    return(true);
                }
                catch (Exception ex)
                {
                    Utils.MessageBox("Сетевая ошибка! Проверьте подключение к интернету и повторите запрос.", this);
                    return(false);
                }
            }
            else
            {
                Utils.MessageBox("Обновление невозможно. Проверьте подключение к интернету и повторите запрос.", this);
                return(false);
            }
        }

        public async void key_exchange(List <MyDialog> newDialos)
        {
            ContactsController.instance.CreateTable();
            foreach (var d in newDialos)
            {
                List <AccessFlags> acs = new List <AccessFlags>();

                List <MessageFlags> flgs = new List <MessageFlags>();
                flgs.Add(MessageFlags.Key);

                Message m = new Message
                {
                    contentP  = AccountsController.mainAccP.openKeyRsaP,
                    senderP   = AccountsController.mainAccP.emailP,
                    receiverP = d.receiverP == AccountsController.mainAccP.emailP ? d.senderP : d.receiverP,
                    flags     = flgs,
                    timeP     = DateTime.Now.ToString()
                };
                if (d.lastMessage.receiverP == AccountsController.mainAccP.emailP)
                {
                    if (d.lastMessage.access[0] == AccessFlags.None)
                    {
                        acs.Add(AccessFlags.Special);
                        m.access = acs;
                        await MessagingController.instance.SendMessage(m, d.dialogName, this);
                    }
                    Contact contact = ContactsController.instance.FindContact(d.lastMessage.senderP);
                    if (contact == null)
                    {
                        ContactsController.instance.SaveItem(new Contact
                        {
                            contactRsaOpenKeyP = d.lastMessage.contentP,
                            contactAddressP    = d.lastMessage.senderP,
                            contactNameP       = "user name",
                            deletedP           = false,
                            dialogNameP        = d.dialogName
                        });
                    }
                    else
                    {
                        if (contact.contactRsaOpenKeyP == null)
                        {
                            contact.contactRsaOpenKeyP = d.lastMessage.contentP;
                            ContactsController.instance.SaveItem(contact);
                        }
                    }
                    await FirebaseController.instance.InsertKey(AccountsController.mainAccP.emailP, d.lastMessage.senderP, d.lastMessage.contentP,
                                                                this);

                    //}
                }
            }
        }

        public async void key_exchange(Message newM)
        {
            ContactsController.instance.CreateTable();
            //foreach (var d in newDialos)
            //{
            List <AccessFlags> acs = new List <AccessFlags>();
            /*acs.Add(AccessFlags.None);*/
            List <MessageFlags> flgs = new List <MessageFlags>();

            flgs.Add(MessageFlags.Key);

            Message m = new Message
            {
                contentP  = AccountsController.mainAccP.openKeyRsaP,
                senderP   = AccountsController.mainAccP.emailP,
                receiverP = newM.receiverP == AccountsController.mainAccP.emailP ? newM.senderP : newM.receiverP,
                flags     = flgs,
                timeP     = DateTime.Now.ToString()
            };

            if (newM.receiverP == AccountsController.mainAccP.emailP)
            {
                if (newM.access[0] == AccessFlags.None)
                {
                    acs.Add(AccessFlags.Special);
                    m.access = acs;
                    await MessagingController.instance.SendMessage(m, newM.dialogName, this);
                }
                Contact contact = ContactsController.instance.FindContact(newM.senderP);
                if (contact == null)
                {
                    ContactsController.instance.SaveItem(new Contact
                    {
                        contactRsaOpenKeyP = newM.contentP,
                        contactAddressP    = newM.senderP,
                        contactNameP       = "user name",
                        deletedP           = false,
                        dialogNameP        = newM.dialogName
                    });
                }
                else
                {
                    if (contact.contactRsaOpenKeyP == null)
                    {
                        contact.contactRsaOpenKeyP = newM.contentP;
                        ContactsController.instance.SaveItem(contact);
                    }
                }
                //будет выполняться постоянно пока в переписке нет писем??
                await FirebaseController.instance.InsertKey(AccountsController.mainAccP.emailP, newM.senderP, newM.contentP,
                                                            this);

                //}
            }

            //}
        }
Ejemplo n.º 9
0
        protected async override void OnCreate(Bundle savedInstanceState)
        {
            try
            {
                base.OnCreate(savedInstanceState);
                SetContentView(Resource.Layout.dialog);

                loadProgress   = FindViewById <ProgressBar>(Resource.Id.loadMessProgress);
                messageContent = FindViewById <EditText>(Resource.Id.edittext_chatbox);
                send           = FindViewById <Button>(Resource.Id.send);

                connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
                networkInfo         = null;

                dialog   = Intent.GetStringExtra("dialogName");
                receiver = Intent.GetStringExtra("receiver");
                flag     = Intent.GetIntExtra("flag", 0);
                SupportActionBar.SetHomeButtonEnabled(true);
                SupportActionBar.SetDisplayHomeAsUpEnabled(true);
                SupportActionBar.SetBackgroundDrawable(new ColorDrawable(Color.ParseColor("#2196f3")));
                ContactsController.instance.CreateTable();
                if (receiver != null)
                {
                    if (ContactsController.instance.ReturnContactName(receiver) != null)
                    {
                        SupportActionBar.Title = ContactsController.instance.ReturnContactName(receiver);
                    }
                }

                if (FirebaseController.instance.app == null)
                {
                    FirebaseController.instance.initFireBaseAuth();
                }
                var layoutManager = new LinearLayoutManager(this)
                {
                    Orientation = LinearLayoutManager.Vertical
                };
                recyclerList = FindViewById <RecyclerView>(Resource.Id.reyclerview_message_list);
                recyclerList.SetLayoutManager(layoutManager);

                MessagingController.instance.ReturnLastMessages(dialog, this);

                MessagesController.instance.CreateTable();
                messageList = MessagesController.instance.GetItems().ToList().FindAll(x => x.dialogName == dialog);

                loadProgress.Visibility = ViewStates.Visible;
                bool result = await fill_list();

                loadProgress.Visibility = ViewStates.Invisible;
                adapter = new RecyclerViewAdapter(messageList);

                recyclerList.SetAdapter(adapter);
                recyclerList.ScrollToPosition(messageList.Count() - 1);

                networkInfo = connectivityManager.ActiveNetworkInfo;
                if (networkInfo != null && networkInfo.IsConnected == true)
                {
                    FirebaseDatabase databaseInstance = FirebaseDatabase.GetInstance(FirebaseController.instance.app);
                    var userNode        = databaseInstance.GetReference("chats");
                    DatabaseReference u = userNode.Child(dialog);
                    u.AddValueEventListener(this);
                }

                send.Click += async delegate
                {
                    if (messageContent.Text != "" && messageContent.Text != " ")
                    {
                        networkInfo = connectivityManager.ActiveNetworkInfo;
                        if (networkInfo != null && networkInfo.IsConnected == true)
                        {
                            loadProgress.Visibility = ViewStates.Visible;

                            List <MessageFlags> flags = new List <MessageFlags>();
                            if (encryption)
                            {
                                flags.Add(MessageFlags.Encoded);
                            }
                            else
                            {
                                flags.Add(MessageFlags.NotEncoded);
                            }

                            List <AccessFlags> acess = new List <AccessFlags>();
                            acess.Add(AccessFlags.NotRead);
                            lastMessage = new Message
                            {
                                //contentP = messageContent.Text,
                                senderP    = AccountsController.mainAccP.emailP,
                                flags      = flags,
                                access     = acess,
                                receiverP  = receiver,
                                timeP      = DateTime.Now.ToString(),
                                dialogName = dialog
                            };
                            if (!encryption)
                            {
                                lastMessage.contentP = messageContent.Text;
                            }
                            else
                            {
                                CryptoProvider c = new CryptoProvider();
                                if (ContactsController.instance.FindContact(receiver).contactRsaOpenKeyP != null &&
                                    ContactsController.instance.FindContact(receiver).contactRsaOpenKeyP != "no key")
                                {
                                    lastMessage.contentP = c.Encrypt(messageContent.Text, ContactsController.instance.FindContact(receiver).contactRsaOpenKeyP);
                                    lastMessage.decodedP = messageContent.Text;
                                    MessagesController.instance.CreateTable();
                                    MessagesController.instance.SaveItem(lastMessage, true);
                                }
                                else
                                {
                                    Utils.MessageBox("Невозможно отправить зашифрованное сообщение! Собеседник не предоставил соотетствующий ключ.", this);
                                    loadProgress.Visibility = ViewStates.Invisible;
                                    return;
                                }
                            }
                            Task <bool> sendTask = MessagingController.instance.SendMessage(lastMessage, dialog, this);
                            bool        sent     = await sendTask;
                            if (sent)
                            {
                                messageContent.Text = "";
                                recyclerList.ScrollToPosition(messageList.Count() - 1);
                            }
                            else
                            {
                                Utils.MessageBox("error", this);
                            }
                            loadProgress.Visibility = ViewStates.Invisible;
                        }
                        else
                        {
                            Utils.MessageBox("Ошибка! Проверьте интернет-соединение.", this);
                        }
                    }
                };
                if (DialogsController.currDialP.lastMessage.access[0] == AccessFlags.Deleted)
                {
                    send.Visibility           = ViewStates.Invisible;
                    messageContent.Visibility = ViewStates.Invisible;
                }
            }
            catch (Exception ex)
            {
                Utils.MessageBox("Произошла сетевая ошибка! Проверьте подключение к интернету и повторите позже.", this);
            }


            // Create your application here
        }
Ejemplo n.º 10
0
        public async void OnDataChange(DataSnapshot snapshot)
        {
            try
            {
                IEnumerable <DataSnapshot> items = snapshot.Children?.ToEnumerable <DataSnapshot>();
                List <DataSnapshot>        t     = items.ToList();

                if (flag == 0)
                {
                    var a    = t.Last().Children.ToEnumerable <DataSnapshot>().ToList();
                    var flag = a[2].Child("0").Value;
                    List <MessageFlags> fls = new List <MessageFlags>();
                    fls.Add((MessageFlags)Convert.ToInt32(flag.ToString()));

                    var access             = a[0].Child("0").Value;
                    List <AccessFlags> acs = new List <AccessFlags>();
                    acs.Add((AccessFlags)Convert.ToInt32(access.ToString()));

                    if (a[4].Value.ToString() != AccountsController.mainAccP.emailP && Convert.ToInt32(access.ToString()) == 2)
                    {
                        await MessagingController.instance.UpdateFlag(t.Last().Key, dialog, this);

                        DialogsController.instance.CreateTable();
                        DialogsController.instance.UpdateItem(dialog);
                        DialogsController.currDialP = new MyDialog();
                    }

                    Message m = new Message
                    {
                        flags     = fls,
                        receiverP = a[3].Value.ToString(),
                        senderP   = a[4].Value.ToString(),
                        timeP     = a[5].Value.ToString(),
                        access    = acs
                    };
                    if (fls[0] == MessageFlags.Encoded && m.senderP != AccountsController.mainAccP.emailP)
                    {
                        CryptoProvider c = new CryptoProvider();
                        m.contentP = c.Decrypt(a[1].Value.ToString(), AccountsController.mainAccP.privateKeyRsaP);
                    }
                    else
                    {
                        m.contentP = a[1].Value.ToString();
                    }

                    if (messageList.Find(x => x.timeP == m.timeP && x.contentP == m.contentP) == null)
                    {
                        if (messageList == null)
                        {
                            messageList = new List <Message>();
                        }
                        messageList.Add(m);
                        DialogsController.currDialP = new MyDialog();

                        /*DialogsController.currDialP = new MyDialog
                         * {
                         *  dialogName = dialog,
                         *  lastMessage = m,
                         *  contentP = m.contentP,
                         *  senderP = m.senderP,
                         *  receiverP = m.receiverP,
                         *  timeP = m.timeP,
                         *  accessFlag = Convert.ToInt32(m.access[0]),
                         *  messageFlag = Convert.ToInt32(m.flags[0])
                         * };*/

                        adapter = new RecyclerViewAdapter(messageList);
                        recyclerList.SetAdapter(adapter);
                        recyclerList.ScrollToPosition(messageList.Count() - 1);
                    }
                }
                else
                {
                    if (flag == 1)
                    {
                        List <DataSnapshot> results = new List <DataSnapshot>();
                        List <DataSnapshot> temp    = t.FindAll(x => x.Children.ToEnumerable <DataSnapshot>().ToList().Count > 5);
                        foreach (var i in temp)
                        {
                            var a = i.Children.ToEnumerable <DataSnapshot>().ToList();
                            if (a.Find(x => x.Key == "senderP" &&
                                       x.Value.ToString() != AccountsController.mainAccP.emailP) != null &&
                                a.Find(x => x.Key == "access" && Convert.ToInt32(x.Child("0").Value.ToString()) == 2) != null)
                            {
                                results.Add(i);
                            }
                        }
                        foreach (var k in results)
                        {
                            //flag = -1;
                            await MessagingController.instance.UpdateFlag(k.Key, dialog, this);

                            DialogsController.instance.CreateTable();
                            DialogsController.instance.UpdateItem(dialog);
                            DialogsController.currDialP = new MyDialog();
                        }
                        flag = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.MessageBox(ex.Message, this);
            }
        }