Exemplo n.º 1
0
        private async void SendMessage(object sender, KeyEventArgs e)
        {
            //SendMessage
            if (e.KeyCode != Keys.Enter || e.Shift || !messageTextBox.Visible)
            {
                return;
            }
            e.SuppressKeyPress = true; //2015.05.21.
            if (messageTextBox.Text.Length == 0)
            {                          //2015.05.21.
                return;
            }
            messageTextBox.ReadOnly = true;
            double time = Program.DateTimeToUnixTime(DateTime.Now);

            if (ChatPartners.Any(entry => entry.UserID != CurrentUser.UserID) && !await Networking.SendChatMessage(this, messageTextBox.Text, time)) //UserID==CurrentUser.UserID: 2015.05.23.
            {
                MessageBox.Show(Language.Translate(Language.StringID.Networking_Alone));
            }
            else //else: 2014.10.31.
            {
                recentMsgTextBox.GoEnd(); //2015.06.16.
                ShowReceivedMessageT(UserInfo.Select(CurrentUser.UserID), messageTextBox.Text, time);
                messageTextBox.Text = "";
            }
            messageTextBox.Select(); //2014.12.13.
            messageTextBox.ReadOnly = false;
        }
            public void Run()
            {
                while (MainForm.PartnerListUpdateThread != null && Program.MainThread.IsAlive)
                {
                    do
                    {
                        PacketFormat pf;
                        IPEndPoint   remoteEP;
                        if (!Networking.ReceiveUpdates(out pf, out remoteEP))
                        {
                            break;
                        }
                        IPEndPoint SendBackEP = new IPEndPoint(remoteEP.Address, pf.Port); //2015.05.10.
                        bool       Break      = false;
                        switch (pf.PacketType)
                        {
                        case UpdateType.ListUpdate:
                        {
                            Networking.ParseUpdateInfo(new string[1][] { ((PDListUpdate)pf.EData).Strings });
                            new PacketSender(new PDListUpdate(true), pf.ID).Send(SendBackEP);
                            break;
                        }

                        case UpdateType.LoginUser:
                        {
                            PDLoginUser data    = (PDLoginUser)pf.EData;
                            string      tmpresp = Networking.SendRequest(Networking.RequestType.CheckUser, pf.EUserID.ToString(), 0, true);    //2014.09.19.
                            if (tmpresp == "Fail")
                            {
                                Break = true;
                                break;         //Nem küld el neki semmit, hanem újra várja a packet-eket
                            }
                            else if (tmpresp != "Success")
                            {
                                MessageBox.Show("LoginUser:\n" + tmpresp);
                                Break = true;
                                break;
                            }

                            if (!UserInfo.IPs.Any(entry => entry == SendBackEP))
                            {
                                UserInfo.IPs.Add(SendBackEP);
                            }
                            List <string> strs = new List <string>();
                            foreach (var uinfo in data.UserInfos)
                            {
                                int      uid        = uinfo.Key;
                                int      updatetime = uinfo.Value;
                                UserInfo user       = UserInfo.Select(uid);
                                if (user == null)
                                {
                                    continue;
                                }
                                strs.Add(user.ToString());         //Egybe rakja felhasználónként, de amikor megkapja, ugyanúgy szétválogatja majd
                            }
                            new PacketSender(new PDLoginUser(strs.ToArray()), pf.ID).Send(SendBackEP);
                            break;
                        }

                        case UpdateType.LogoutUser:
                        {         //2015.05.10. - Felesleges elküldenie az IP-címeket, mint a bejelentkezésnél
                            UserInfo.Select(pf.EUserID).State = 0;
                            new PacketSender(new PDLogoutUser(), pf.ID).Send(SendBackEP);
                            break;
                        }

                        case UpdateType.GetImage:
                        {
                            PDGetImage data = (PDGetImage)pf.EData;
                            UserInfo   user = UserInfo.Select(data.UserID);
                            bool       success;
                            byte[]     imagedata;
                            if (user.PicUpdateTime > data.PicUpdateTime)
                            {
                                success = true;
                                var ms = new MemoryStream();
                                if (user.Image != null)
                                {
                                    user.Image.Save(ms, ImageFormat.Tiff); //2015.05.30.
                                    imagedata = ms.ToArray();              //2015.05.30.
                                }
                                else
                                {
                                    success   = false;
                                    imagedata = new byte[0];
                                }
                            }
                            else
                            {
                                success   = false;
                                imagedata = new byte[0];
                            }
                            new PacketSender(new PDGetImage(success, user.PicUpdateTime, imagedata), pf.ID).Send(SendBackEP);
                        }
                        break;

                        case UpdateType.UpdateMessages:
                        {
                            PDUpdateMessages data    = (PDUpdateMessages)pf.EData;
                            bool             success = true;
                            var userinfos            = data.Users.Select(entry => UserInfo.Select(entry)); //2015.06.16.
                            if (userinfos.Except(UserInfo.KnownUsers.Where(entry => entry.IsPartner && entry.UserID != CurrentUser.UserID)).Count() == 0)
                            {                                                                              //2015.06.16. - Leellenőrzi, hogy van-e ismerőse a listában
                                success = false;                                                           //2015.06.25.
                            }
                            else
                            {
                                ChatPanel cp = ChatPanel.GetChatPanelByUsers(userinfos);
                                if (cp == null)                                                                //2015.05.16.
                                {
                                    cp = ChatPanel.Create(data.Users.Select(entry => UserInfo.Select(entry))); //2015.05.16.
                                }
                                cp.ShowReceivedMessageT(UserInfo.Select(pf.EUserID), data.Message, data.Time);
                            }
                            new PacketSender(new PDUpdateMessages(success), pf.ID).Send(SendBackEP);
                        }
                        break;

                        case UpdateType.SetKey:
                            break;                 //TODO

                        case UpdateType.SendImage: //2015.06.25.
                        {
                            PDSendImage data      = (PDSendImage)pf.EData;
                            bool        success   = true;
                            var         userinfos = data.Users.Select(entry => UserInfo.Select(entry));
                            if (userinfos.Except(UserInfo.KnownUsers.Where(entry => entry.IsPartner && entry.UserID != CurrentUser.UserID)).Count() == 0)
                            {
                                success = false;
                            }
                            ChatPanel cp = ChatPanel.GetChatPanelByUsers(userinfos);
                            if (cp == null)
                            {
                                cp = ChatPanel.Create(data.Users.Select(entry => UserInfo.Select(entry)));
                            }
                            cp.ShowReceivedImageT(UserInfo.Select(pf.EUserID), data.Image, data.Time);
                            new PacketSender(new PDSendImage(success), pf.ID).Send(SendBackEP);
                        }
                        break;

                        case UpdateType.SendFile:     //2015.06.30.
                        {
                            PDSendFile data      = (PDSendFile)pf.EData;
                            bool       success   = true;
                            var        userinfos = data.Users.Select(entry => UserInfo.Select(entry));
                            if (userinfos.Except(UserInfo.KnownUsers.Where(entry => entry.IsPartner && entry.UserID != CurrentUser.UserID)).Count() == 0)
                            {
                                success = false;
                            }
                            ChatPanel cp = ChatPanel.GetChatPanelByUsers(userinfos);
                            if (cp == null)
                            {
                                cp = ChatPanel.Create(data.Users.Select(entry => UserInfo.Select(entry)));
                            }
                            long rprogress = cp.ShowReceivedFileT(UserInfo.Select(pf.EUserID), data.File, data.Time, data.Progress);
                            new PacketSender(new PDSendFile(success, rprogress, CurrentUser.IPs, CurrentUser.Port), pf.ID).Send(SendBackEP);
                        }
                        break;

                        default:                                                                                            //2015.06.25.
                            throw new NotImplementedException("This type (" + pf.PacketType + ") is not handled in code."); //2015.06.25.
                        }
                        if (Break)
                        {
                            break;
                        }
                    } while (false);
                }
            }
Exemplo n.º 3
0
        public MainForm()
        {
            BeforeLogin.SetText("Starting...");
            Program.MainF = this;
            InitializeComponent();
            Thread.CurrentThread.Name  = "Main Thread";
            toolStripMenuItem4.Enabled = false;           //2014.04.12.
            toolStripMenuItem8.Enabled = false;           //2014.04.12.

            this.WindowState = FormWindowState.Minimized; //2014.04.19.

            BeforeLogin.SetText("Loading program settings...");
            Storage.Load(false); //Töltse be a nyelvet, legutóbb használt E-mail-t...

            BeforeLogin.SetText("Checking available ports...");
            //2014.09.04. - Amint lehet állítsa be a helyes IP-t, majd azt hagyja úgy, akármi történjék
            while (true)
            {
                if (IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners().Select(entry => entry.Port).Contains(Int32.Parse(Storage.Settings["port"])))
                {
                    Storage.Settings["port"] = (Int32.Parse(Storage.Settings["port"]) + 1).ToString();
                }
                else
                {
                    break;
                }
            }
            Networking.ReceiverConnection = new UdpClient(Int32.Parse(Storage.Settings["port"])); //2014.09.04.
            Networking.SenderConnection.AllowNatTraversal(true);                                  //2014.09.04.

            BeforeLogin.SetText("Loading languages...");
            new Language();

            BeforeLogin.SetText(Language.Translate("beforelogin_translatemainf"));
            #region Helyi beállitás
            //try
            //{
            fájlToolStripMenuItem.Text              = Language.Translate("menu_file");
            Language.ReloadEvent                   += delegate { fájlToolStripMenuItem.Text = Language.Translate("menu_file"); };
            kijelentkezésToolStripMenuItem.Text     = Language.Translate("menu_file_logout");
            Language.ReloadEvent                   += delegate { kijelentkezésToolStripMenuItem.Text = Language.Translate("menu_file_logout"); };
            toolStripMenuItem1.Text                 = Language.Translate("menu_file_loginnewuser");
            Language.ReloadEvent                   += delegate { toolStripMenuItem1.Text = Language.Translate("menu_file_loginnewuser"); };
            állapotToolStripMenuItem.Text           = Language.Translate("menu_file_status");
            Language.ReloadEvent                   += delegate { állapotToolStripMenuItem.Text = Language.Translate("menu_file_status"); };
            elérhetőToolStripMenuItem.Text          = Language.Translate("menu_file_status_online");
            Language.ReloadEvent                   += delegate { elérhetőToolStripMenuItem.Text = Language.Translate("menu_file_status_online"); };
            elfoglaltToolStripMenuItem.Text         = Language.Translate("menu_file_status_busy");
            Language.ReloadEvent                   += delegate { elfoglaltToolStripMenuItem.Text = Language.Translate("menu_file_status_busy"); };
            nincsAGépnélToolStripMenuItem.Text      = Language.Translate("menu_file_status_away");
            Language.ReloadEvent                   += delegate { nincsAGépnélToolStripMenuItem.Text = Language.Translate("menu_file_status_away"); };
            rejtveKapcsolódikToolStripMenuItem.Text = Language.Translate("menu_file_status_hidden");
            Language.ReloadEvent                   += delegate { rejtveKapcsolódikToolStripMenuItem.Text = Language.Translate("menu_file_status_hidden"); };
            fájlKüldéseToolStripMenuItem.Text       = Language.Translate("menu_file_sendfile");
            Language.ReloadEvent                   += delegate { fájlKüldéseToolStripMenuItem.Text = Language.Translate("menu_file_sendfile"); };
            beérkezettFájlokMappájánakMegnyitásaToolStripMenuItem.Text = Language.Translate("menu_file_openreceivedfiles");
            Language.ReloadEvent += delegate { beérkezettFájlokMappájánakMegnyitásaToolStripMenuItem.Text = Language.Translate("menu_file_openreceivedfiles"); };
            üzenetekElőzményeinekMegtekintéseToolStripMenuItem.Text = Language.Translate("menu_file_openrecentmsgs");
            Language.ReloadEvent         += delegate { üzenetekElőzményeinekMegtekintéseToolStripMenuItem.Text = Language.Translate("menu_file_openrecentmsgs"); };
            bezárásToolStripMenuItem.Text = Language.Translate("menu_file_close");
            Language.ReloadEvent         += delegate { bezárásToolStripMenuItem.Text = Language.Translate("menu_file_close"); };
            kilépésToolStripMenuItem.Text = Language.Translate("menu_file_exit");
            Language.ReloadEvent         += delegate { kilépésToolStripMenuItem.Text = Language.Translate("menu_file_exit"); };

            ismerősökToolStripMenuItem.Text             = Language.Translate("menu_contacts");
            Language.ReloadEvent                       += delegate { ismerősökToolStripMenuItem.Text = Language.Translate("menu_contacts"); };
            ismerősFelvételeToolStripMenuItem.Text      = Language.Translate("menu_contacts_add");
            Language.ReloadEvent                       += delegate { ismerősFelvételeToolStripMenuItem.Text = Language.Translate("menu_contacts_add"); };
            ismerősSzerkesztéseToolStripMenuItem.Text   = Language.Translate("menu_contacts_edit");
            Language.ReloadEvent                       += delegate { ismerősSzerkesztéseToolStripMenuItem.Text = Language.Translate("menu_contacts_edit"); };
            ismerősTörléseToolStripMenuItem.Text        = Language.Translate("menu_contacts_remove");
            Language.ReloadEvent                       += delegate { ismerősTörléseToolStripMenuItem.Text = Language.Translate("menu_contacts_remove"); };
            toolStripMenuItem3.Text                     = Language.Translate("menu_contacts_invite");
            Language.ReloadEvent                       += delegate { toolStripMenuItem3.Text = Language.Translate("menu_contacts_invite"); };
            csoportLétrehozásaToolStripMenuItem.Text    = Language.Translate("menu_contacts_makegroup");
            Language.ReloadEvent                       += delegate { csoportLétrehozásaToolStripMenuItem.Text = Language.Translate("menu_contacts_makegroup"); };
            kategóriaLétrehozásaToolStripMenuItem.Text  = Language.Translate("menu_contacts_makecategory");
            Language.ReloadEvent                       += delegate { kategóriaLétrehozásaToolStripMenuItem.Text = Language.Translate("menu_contacts_makecategory"); };
            kategóriaSzerkesztéseToolStripMenuItem.Text = Language.Translate("menu_contacts_editcategory");
            Language.ReloadEvent                       += delegate { kategóriaSzerkesztéseToolStripMenuItem.Text = Language.Translate("menu_contacts_editcategory"); };
            kategóriaTörléseToolStripMenuItem.Text      = Language.Translate("menu_contacts_removecategory");
            Language.ReloadEvent                       += delegate { kategóriaTörléseToolStripMenuItem.Text = Language.Translate("menu_contacts_removecategory"); };

            műveletekToolStripMenuItem.Text                      = Language.Translate("menu_operations");
            Language.ReloadEvent                                += delegate { műveletekToolStripMenuItem.Text = Language.Translate("menu_operations"); };
            azonnaliÜzenetKüldéseToolStripMenuItem.Text          = Language.Translate("menu_operations_sendmsg");
            Language.ReloadEvent                                += delegate { azonnaliÜzenetKüldéseToolStripMenuItem.Text = Language.Translate("menu_operations_sendmsg"); };
            egyébKüldéseToolStripMenuItem.Text                   = Language.Translate("menu_operations_sendother");
            Language.ReloadEvent                                += delegate { egyébKüldéseToolStripMenuItem.Text = Language.Translate("menu_operations_sendother"); };
            emailKüldéseToolStripMenuItem.Text                   = Language.Translate("menu_operations_sendother_sendmail");
            Language.ReloadEvent                                += delegate { emailKüldéseToolStripMenuItem.Text = Language.Translate("menu_operations_sendother_sendmail"); };
            fájlKüldéseToolStripMenuItem1.Text                   = Language.Translate("menu_file_sendfile"); //Ugyanaz a szöveg
            Language.ReloadEvent                                += delegate { fájlKüldéseToolStripMenuItem1.Text = Language.Translate("menu_file_sendfile"); };
            ismerősSzámitógépénekFelhivásaToolStripMenuItem.Text = Language.Translate("menu_operations_callcontact");
            Language.ReloadEvent                                += delegate { ismerősSzámitógépénekFelhivásaToolStripMenuItem.Text = Language.Translate("menu_operations_callcontact"); };
            videóhivásInditásaToolStripMenuItem.Text             = Language.Translate("menu_operations_videocall");
            Language.ReloadEvent                                += delegate { videóhivásInditásaToolStripMenuItem.Text = Language.Translate("menu_operations_videocall"); };
            onlineFájlokMegtekintéseToolStripMenuItem.Text       = Language.Translate("menu_operations_showonlinefiles");
            Language.ReloadEvent                                += delegate { onlineFájlokMegtekintéseToolStripMenuItem.Text = Language.Translate("menu_operations_showonlinefiles"); };
            közösJátékToolStripMenuItem.Text                     = Language.Translate("menu_operations_playgame");
            Language.ReloadEvent                                += delegate { közösJátékToolStripMenuItem.Text = Language.Translate("menu_operations_playgame"); };
            távsegitségKéréseToolStripMenuItem.Text              = Language.Translate("menu_operations_askforhelp");
            Language.ReloadEvent                                += delegate { távsegitségKéréseToolStripMenuItem.Text = Language.Translate("menu_operations_askforhelp"); };

            eszközökToolStripMenuItem.Text                 = Language.Translate("menu_tools");
            Language.ReloadEvent                          += delegate { eszközökToolStripMenuItem.Text = Language.Translate("menu_tools"); };
            mindigLegfelülToolStripMenuItem.Text           = Language.Translate("menu_tools_alwaysontop");
            Language.ReloadEvent                          += delegate { mindigLegfelülToolStripMenuItem.Text = Language.Translate("menu_tools_alwaysontop"); };
            hangulatjelekToolStripMenuItem.Text            = Language.Translate("menu_tools_emoticons");
            Language.ReloadEvent                          += delegate { hangulatjelekToolStripMenuItem.Text = Language.Translate("menu_tools_emoticons"); };
            megjelenitendőKépVáltásaToolStripMenuItem.Text = Language.Translate("menu_tools_changeimage");
            Language.ReloadEvent                          += delegate { megjelenitendőKépVáltásaToolStripMenuItem.Text = Language.Translate("menu_tools_changeimage"); };
            háttérMódositásaToolStripMenuItem.Text         = Language.Translate("menu_tools_changebackground");
            Language.ReloadEvent                          += delegate { háttérMódositásaToolStripMenuItem.Text = Language.Translate("menu_tools_changebackground"); };
            hangokÉsVideóBeállitásaToolStripMenuItem.Text  = Language.Translate("menu_tools_voicevideosettings");
            Language.ReloadEvent                          += delegate { hangokÉsVideóBeállitásaToolStripMenuItem.Text = Language.Translate("menu_tools_voicevideosettings"); };
            beállitásokToolStripMenuItem.Text              = Language.Translate("menu_tools_settings");
            Language.ReloadEvent                          += delegate { beállitásokToolStripMenuItem.Text = Language.Translate("menu_tools_settings"); };

            súgóToolStripMenuItem.Text      = Language.Translate("menu_help");
            Language.ReloadEvent           += delegate { súgóToolStripMenuItem.Text = Language.Translate("menu_help"); };
            témakörökToolStripMenuItem.Text = Language.Translate("menu_help_contents");
            Language.ReloadEvent           += delegate { témakörökToolStripMenuItem.Text = Language.Translate("menu_help_contents"); };
            aSzolgáltatásÁllapotsaToolStripMenuItem.Text = Language.Translate("menu_help_status");
            Language.ReloadEvent += delegate { aSzolgáltatásÁllapotsaToolStripMenuItem.Text = Language.Translate("menu_help_status"); };
            adatvédelmiNyilatkozatToolStripMenuItem.Text = Language.Translate("menu_help_privacypolicy");
            Language.ReloadEvent += delegate { adatvédelmiNyilatkozatToolStripMenuItem.Text = Language.Translate("menu_help_privacypolicy"); };
            használatiFeltételekToolStripMenuItem.Text = Language.Translate("menu_help_termsofuse");
            Language.ReloadEvent += delegate { használatiFeltételekToolStripMenuItem.Text = Language.Translate("menu_help_termsofuse"); };
            visszaélésBejelentéseToolStripMenuItem.Text = Language.Translate("menu_help_report");
            Language.ReloadEvent += delegate { visszaélésBejelentéseToolStripMenuItem.Text = Language.Translate("menu_help_report"); };
            segitsenAProgramTökéletesitésébenToolStripMenuItem.Text = Language.Translate("menu_help_improveprogram");
            Language.ReloadEvent         += delegate { segitsenAProgramTökéletesitésébenToolStripMenuItem.Text = Language.Translate("menu_help_improveprogram"); };
            névjegyToolStripMenuItem.Text = Language.Translate("menu_help_about");
            Language.ReloadEvent         += delegate { névjegyToolStripMenuItem.Text = Language.Translate("menu_help_about"); };

            textBox1.Text = Language.Translate("searchbar", textBox1);
            //contactList.Items[0].SubItems[0].Text = Language.Translate("loading"); - 2014.08.28. - Nincs már rá szükség (hibát is ír, mivel nincs listaelem)

            //üzenetküldésToolStripMenuItem.Text = Language.Translate("menu_operations_sendmsg");
            //emailKüldéseemailToolStripMenuItem.Text = Language.Translate("contact_sendemail");
            //toolStripMenuItem2.Text = Language.Translate("contact_copyemail");
            //információToolStripMenuItem.Text = Language.Translate("contact_info");
            //ismerősLetiltásaToolStripMenuItem.Text = Language.Translate("contact_block");
            //ismerősTörléseToolStripMenuItem.Text = Language.Translate("contact_remove"); - Kétszer benne volt, ugyanilyen névvel, csak 1-re végződve lett volna a megfelelő
            //becenévSzerkesztéseToolStripMenuItem.Text = Language.Translate("contact_editname");
            //eseményértesitésekToolStripMenuItem.Text = Language.Translate("contact_eventnotifications");
            //beszélgetésnaplóMegnyitásaToolStripMenuItem.Text = Language.Translate("contact_openchatlog");

            toolStripMenuItem4.Text = Language.Translate("iconmenu_show");
            Language.ReloadEvent   += delegate { toolStripMenuItem4.Text = Language.Translate("iconmenu_show"); };
            toolStripMenuItem8.Text = Language.Translate("menu_file_logout");
            Language.ReloadEvent   += delegate { toolStripMenuItem8.Text = Language.Translate("menu_file_logout"); };
            toolStripMenuItem9.Text = Language.Translate("menu_file_exit");
            Language.ReloadEvent   += delegate { toolStripMenuItem9.Text = Language.Translate("menu_file_exit"); };
            //}
            //catch
            //{
            //MessageBox.Show("Error while loading translations.");
            //}

            LoadMenu(MenuType.ChatIconMenu); //2014.12.12.
            LoadMenu(MenuType.PartnerMenu);  //2014.12.13.
            #endregion

            BeforeLogin.SetText(Language.Translate("beforelogin_loadtextformat"));
            //2014.05.16.
            new TextFormat();

            BeforeLogin.SetText(Language.Translate("beforelogin_checkforupdates"));
            //2014.04.25.
            string response = Networking.SendRequest("checkforupdates",
                                                     Assembly.GetExecutingAssembly().GetName().Version.ToString().Replace(".", ""),
                                                     0, false);
            if (response == "outofdate")
            {
                var res = MessageBox.Show(Language.Translate("outofdate"), Language.Translate("outofdate_caption"), MessageBoxButtons.YesNo);
                if (res == DialogResult.Yes)
                //System.Diagnostics.Process.Start("http://msger.url.ph/download.php?version=latest");
                //(new UpdateDialog()).Show(); //2014.12.13. - Elvileg át lehet nevezni a programot, miközben fut (ami érdekes) - De inkább csinálok külön programot
                { //2014.12.13.
                    Process.Start("Updater.exe", "\"" + Language.Translate("updater") + "\" \"" + Language.Translate("updater_info") + "\"");
                    Program.Exit(false);
                }
            }
            else if (response != "fine")
            {
                MessageBox.Show(Language.Translate("error") + ": " + response);
            }

            //BeforeLogin.SetText(Language.Translate("beforelogin_server")); //2015.01.07.

            //2014.09.06.

            /*if (Storage.Settings["isserver"] == "")
             * {
             *  if (MessageBox.Show(Language.Translate("isserver_msg"), "", MessageBoxButtons.YesNo) == DialogResult.Yes)
             *      Storage.Settings["isserver"] = "1";
             *  else
             *      Storage.Settings["isserver"] = "0";
             * }*/

            /*if(Storage.Settings["isserver"]=="1") //2015.01.07.
             * {
             *  NATUPNPLib.UPnPNAT upnpnat = new NATUPNPLib.UPnPNAT();
             *  NATUPNPLib.IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection;
             *  if (mappings == null)
             *  {
             *      //MessageBox.Show(Language.Translate("portforward_noaccess"));
             *  }
             *  //else
             *  //{
             *      foreach (NATUPNPLib.IStaticPortMapping mapping in mappings)
             *      {
             *          if (mapping.Protocol == "UDP" && mapping.InternalPort.ToString() == Storage.Settings["port"])
             *          {
             *              if (MessageBox.Show(Language.Translate("portforward_existsremove"), "", MessageBoxButtons.YesNo) == DialogResult.Yes)
             *                  mappings.Remove(mapping.ExternalPort, "UDP");
             *              else
             *                  Storage.Settings["port"] = (Int32.Parse(Storage.Settings["port"]) + 1).ToString();
             *          }
             *
             *      }
             *      int port = int.Parse(Storage.Settings["port"]);
             *      mappings.Add(port, "UDP", port, Dns.GetHostEntry(Dns.GetHostName()).AddressList.Single(entry =>
             *      entry.AddressFamily == AddressFamily.InterNetwork
             *          && (entry.ToString().Contains("192.168.0.") || entry.ToString().Contains("192.168.1.") || entry.ToString().Contains("10.0.0.") || entry.ToString().Contains("172.16.0.")) //Helyi IP-k
             *          ).ToString(), true, "MSGer.tk chat program");
             *      Networking.ReceiverConnection = new UdpClient(Int32.Parse(Storage.Settings["port"]));
             *  //}
             * }*/

            //TO!DO: Nem kell az "isserver" beállítás, először kliensként próbáljon meg csatlakozni, majd szerverként fogadja az új klienseket
            // a pwnat segítségével
            //2015.03.15. - Nem kell az sem: IPv6 - A legtöbb eszköz már támogatja

            BeforeLogin.SetText(Language.Translate("beforelogin_loginform"));
            try
            {
                LoginDialog = new LoginForm();
                BeforeLogin.Destroy();
                LoginDialog.ShowDialog();
            }
            catch (Exception e)
            {
                ErrorHandling.FormError(LoginDialog, e);
            }
            //Nézzük, sikerült-e
            if (CurrentUser.UserID == 0)
            {
                return;                  //2014.09.06.
            }
            contactList.Enabled = false; //2014.03.05.
            MainThread          = Thread.CurrentThread;

            // Create the thread object, passing in the Alpha.Beta method
            // via a ThreadStart delegate. This does not start the thread.
            LThread      = new Thread(new ThreadStart(new UpdateListAndChat().Run));
            LThread.Name = "Update Partnerlist and Chat";

            /*Thread keepupthread = new Thread(new ThreadStart(Networking.KeepUpThread));
             * keepupthread.Name = "Keep Up Thread";
             *
             * Thread keepupuserst = new Thread(new ThreadStart(Networking.KeepUpUsersThread)); //2014.09.26.
             * keepupuserst.Name = "Keep Up Users Thread";*/

            Thread networkthread = new Thread(new ThreadStart(Networking.NetworkThread)); //2014.12.31.
            networkthread.Name = "Network Thread";

            Storage.Load(true);                         //2014.08.07.

            if (Storage.Settings["windowstate"] == "1") //2014.04.18. - 2014.08.08.
            {
                this.WindowState = FormWindowState.Maximized;
            }
            else if (Storage.Settings["windowstate"] == "2")
            {
                this.WindowState = FormWindowState.Minimized;
            }
            else if (Storage.Settings["windowstate"] == "3")
            {
                this.WindowState = FormWindowState.Normal;
            }

            taskbarNotifier = new Notifier("popup-bg.bmp", Color.FromArgb(255, 0, 255), "close.bmp", 5000);

            taskbarNotifier.Click      += PopupClick;
            taskbarNotifier.CloseClick += PopupCloseClick;

            toolStripMenuItem4.Enabled = true; //2014.04.12.
            toolStripMenuItem8.Enabled = true; //2014.04.12.

            // Start the thread
            LThread.Start();

            //keepupthread.Start();

            //keepupuserst.Start();

            networkthread.Start();

            //2014.08.19. - Küldje el a bejelentkezés hírét, hogy frissítéseket kapjon

            /*byte[] strb = Encoding.Unicode.GetBytes(CurrentUser.IP.ToString());
             * byte[] tmpfinal = new byte[8 * UserInfo.KnownUsers.Count + strb.Length + 4 + 1]; //Hosszúság, IP, ismert felh. ID, frissítési idő
             * Array.Copy(BitConverter.GetBytes(strb.Length), tmpfinal, 4);
             * Array.Copy(strb, 0, tmpfinal, 4, strb.Length);
             * //if (tmpfinal.Length != 0)
             * for (int i = 0; i < UserInfo.KnownUsers.Count; i++) //Ha a count 0, nem fogja végrehajtani
             * {
             *  byte[] tmptmp = BitConverter.GetBytes(UserInfo.KnownUsers[i].UserID);
             *  Array.Copy(tmptmp, 0, tmpfinal, i * 4 + strb.Length + 4, 4);
             *  tmptmp = BitConverter.GetBytes(UserInfo.KnownUsers[i].LastUpdate);
             *  Array.Copy(tmptmp, 0, tmpfinal, i * 4 + strb.Length + 4, 4);
             * }
             * tmpfinal[tmpfinal.Length - 1] = (Storage.Settings["isserver"] == "1") ? (byte)0x01 : (byte)0x00; //Mivel bejelentkezéstől függetlenül menti el, gépfüggő, hogy itt mit küld el
             * Networking.ParseUpdateInfo(Networking.SendUpdate(Networking.UpdateType.LoginUser, tmpfinal, false));*/

            while (!networkthread.IsAlive)
            {
                ;
            }
            SendLoginToUsers();         //2014.12.18.

            notifyIcon1.Visible = true; //2014.09.22.
            taskbarNotifier.Show("Teszt cím", "Teszt tartalom\nMásodik sor");

            Language.ReloadEvent += delegate { textBox1.Text = Language.Translate("searchbar"); }; //2014.12.22. - Nyelvváltáskor törölni fogja a beírt szöveget
        }
Exemplo n.º 4
0
        public void Run()
        {
            while (MainForm.LThread != null && MainForm.MainThread.IsAlive)
            {
                do
                {
                    object[] retobj = Networking.ReceiveUpdates();
                    if (retobj == null)                          //2014.12.05.
                    {
                        return;                                  //2014.12.05. - Leállt a program
                    }
                    byte[]     resp     = (byte[])retobj[0];     //2014.10.24.
                    IPEndPoint remoteEP = (IPEndPoint)retobj[1]; //2014.10.24.
                    if (resp == null)
                    {
                        break;
                    }
                    byte isresponse;                                                                                              //2014.09.15.
                    Networking.UpdateType updatetype;                                                                             //2014.09.15.
                    int    keyversion;                                                                                            //2014.09.15.
                    int    port;                                                                                                  //2014.12.19.
                    int    userid;                                                                                                //2014.09.15.
                    byte[] data;                                                                                                  //2014.09.15.
                    Networking.ParsePacket(resp, out isresponse, out updatetype, out keyversion, out port, out userid, out data); //2014.09.15.
                    //if (!UserInfo.IPs.Any(entry=>entry.IP==remoteEP) && updatetype != Networking.UpdateType.LoginUser) //2014.10.24.
                    //if (!UserInfo.IPs.Any(entry => entry.IP == remoteEP) && updatetype != Networking.UpdateType.LoginUser) //2014.11.23
                    if (!UserInfo.IPs.Any(entry => entry.Address.Equals(remoteEP.Address)) && //2014.12.19. - A port nem ugyanaz, ráadásul a == nem hívja meg a .Equals metódust
                        updatetype != Networking.UpdateType.LoginUser

                        /*&& updatetype != Networking.UpdateType.CheckConn
                        *  && updatetype != Networking.UpdateType.RequestConn
                        *  && updatetype != Networking.UpdateType.MakeConn
                        *  && updatetype != Networking.UpdateType.MakeConn2*/)
                    {
                        break;
                    }
                    //bool x = UserInfo.IPs.Single().IP.Address.Equals(remoteEP.Address);
                    if (updatetype == Networking.UpdateType.ListUpdate)
                    {
                        //Networking.ParseUpdateInfo(new byte[][] { data }); //2014.09.15.
                        Networking.ParseUpdateInfo(new byte[][] { resp }); //2014.12.22. - A funkció az egész packet-re számít, nem csak a data-ra
                    }
                    else if (updatetype == Networking.UpdateType.UpdateMessages)
                    {
                        string[]        response = Networking.GetStrings(data, 0);
                        string[]        tmp      = response[0].Split(',');
                        List <UserInfo> tmp2     = new List <UserInfo>();
                        tmp2.Add(UserInfo.Select(userid));                                       //Adja hozzá a küldőt is
                        tmp2.AddRange(tmp.Select(entry => UserInfo.Select(Int32.Parse(entry)))); //2014.10.24.
                        //if (tmp2.All(entry => !UserInfo.Select(entry).IsPartner)) //2014.10.24.
                        if (tmp2.All(entry => !entry.IsPartner))                                 //2014.10.31.
                        {
                            break;                                                               //Ha a beszélgetésben nincs ismerőse, akkor nem foglalkozik vele
                        }
                        var cf = ChatPanel.GetChatFormByUsers(tmp2);
                        if (cf == null)
                        {
                            Program.MainF.Invoke((MethodInvoker) delegate
                            {
                                ChatPanel.ChatWindows.Add(new ChatPanel());
                                cf = ChatPanel.ChatWindows[ChatPanel.ChatWindows.Count - 1];
                                cf.ChatPartners.AddRange(tmp2);
                                cf.Init();
                            });
                        }
                        //0 - Résztvevők; 1 - Üzenet; 2 - Üzenetküldés időpontja
                        string[] cmd = response[1].Split(' ');
                        switch (cmd[0])
                        {
                        case "//sendfile":
                            string[]  ipportname   = cmd[1].Split(':');
                            IPAddress ipAddr       = IPAddress.Parse(ipportname[0]);
                            var       permission   = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", SocketPermission.AllPorts);
                            var       ipEndPoint   = new IPEndPoint(ipAddr, Int32.Parse(ipportname[1]));
                            var       receiverSock = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                            receiverSock.Connect(ipEndPoint);
                            var ns = new NetworkStream(receiverSock);
                            var fs = new FileStream(ipportname[2], FileMode.Create);
                            break;
                        }
                        cf.TMessage = "\n" + ((userid == CurrentUser.UserID) ? CurrentUser.Name : UserInfo.Select(userid).Name) + " " + Language.Translate("said") + " (" + Program.UnixTimeToDateTime(response[2]).ToString("yyyy.MM.dd. HH:mm:ss") + "):\n" + response[1] + "\n";
                        Program.MainF.Invoke(new LoginForm.MyDelegate(cf.SetThreadValues));
                    }
                    else if (updatetype == Networking.UpdateType.LoginUser)
                    {
                        string tmpresp = Networking.SendRequest("checkuser", userid.ToString(), 0, true); //2014.09.19.
                        if (tmpresp == "Fail")
                        {
                            break; //Nem küld el neki semmit, hanem újra várja a packet-eket
                        }
                        else if (tmpresp != "Success")
                        {
                            MessageBox.Show("LoginUser:\n" + tmpresp);
                            break;
                        }

                        //int iplen = BitConverter.ToInt32(data, 0);
                        //string ip = Encoding.Unicode.GetString(data, 4, iplen);
                        //IPAddress ip = IPAddress.Parse(Encoding.Unicode.GetString(data, 4, iplen));

                        /*if (!Storage.Settings["ips"].Contains(ip))
                         *  Storage.Settings["ips"] += ";" + ip;*/
                        //var ep = new IPEndPoint(ip, UserInfo.GetPortForIP(ip)); //2014.11.15.
                        //var ep = new IPEndPoint(ip, port); //2014.12.19.
                        var ep = new IPEndPoint(remoteEP.Address, port);
                        //if (!UserInfo.IPs.Any(entry=>entry.IP==ep))
                        if (!UserInfo.IPs.Any(entry => entry == ep))
                        {
                            UserInfo.IPs.Add(ep);
                        }
                        string retstr = "";
                        //for (int i = 4 + iplen; i + 8 < resp.Length; i += 8)
                        for (int i = 0; i + 8 < data.Length; i += 8)
                        {
                            int uid   = BitConverter.ToInt32(data, i);
                            int utime = BitConverter.ToInt32(data, i + 4);
                            if (Storage.LoggedInSettings.ContainsKey("userinfo_" + uid + "_updatetime") && Int32.Parse(Storage.LoggedInSettings["userinfo_" + uid + "_updatetime"]) > utime)
                            {
                                retstr += uid + "_name=" + Storage.LoggedInSettings["userinfo_" + uid + "_name"] + "\n";
                                retstr += uid + "_message=" + Storage.LoggedInSettings["userinfo_" + uid + "_message"] + "\n";
                                retstr += uid + "_state=" + Storage.LoggedInSettings["userinfo_" + uid + "_state"] + "\n";
                                retstr += uid + "_username="******"userinfo_" + uid + "_username"] + "\n";
                                retstr += uid + "_email=" + Storage.LoggedInSettings["userinfo_" + uid + "_email"] + "\n";
                                retstr += uid + "_ispartner=" + Storage.LoggedInSettings["userinfo_" + uid + "_ispartner"] + "\n";
                                //retstr += uid + "_lastupdate=" + Program.DateTimeToUnixTime(DateTime.Now);
                                if (uid != CurrentUser.UserID)                                                                    //2014.11.29.
                                {
                                    retstr += uid + "_lastupdate=" + Storage.LoggedInSettings["userinfo_" + uid + "_lastupdate"]; //2014.11.29. - Arra az időpontra állítsa, amikor ő kapta a frissítést, így ez elvileg az eredeti frissítés időpontját mutatja kb. - Ezért a sajátját biztosan frissen kell tartani
                                }
                                else
                                {
                                    retstr += uid + "_lastupdate=" + Program.DateTimeToUnixTime(DateTime.Now);
                                }
                                //if (i + 1 != (resp.Length - 9) / 8)
                                if (i + 16 < data.Length)
                                {
                                    retstr += "\n";
                                }
                            }
                        }
                        UserInfo.Select(userid).State = 1;
                        Networking.SendUpdate(Networking.UpdateType.LoginUser, Encoding.Unicode.GetBytes(retstr), true);
                    }
                    else if (updatetype == Networking.UpdateType.LogoutUser)
                    { //2014.08.31. 0:32
                        int    len   = BitConverter.ToInt32(data, 0);
                        string ipstr = Encoding.Unicode.GetString(data, 4, len);
                        //Storage.Settings["ips"] = Storage.Settings["ips"].Remove(Storage.Settings["ips"].IndexOf(ipstr), ipstr.Length); //2014.09.22.
                        //var ip = IPAddress.Parse(ipstr);
                        string[] ips = ipstr.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        var      ip  = ips.Select(entry => IPAddress.Parse(entry));
                        //UserInfo.IPs.RemoveWhere(entry => entry.IP.Address == ip && entry.IP.Port == UserInfo.GetPortForIP(entry.IP.Address)); //2014.11.15.
                        UserInfo.IPs.RemoveWhere(entry => entry.Address == ip && entry.Port == port); //2014.11.15. - Port: 2014.12.19.
                    }
                    else if (updatetype == Networking.UpdateType.SetKey)                              //2014.09.09.
                    {                                                                                 //2014.09.22.
                        CurrentUser.KeyIndex = BitConverter.ToInt32(data, 0);
                    }
                    else if (updatetype == Networking.UpdateType.GetImage) //2014.11.01. 0:53
                    {
                        string      tmp           = Path.GetTempPath();
                        List <byte> sendb         = new List <byte>();
                        int         user          = BitConverter.ToInt32(data, 0);
                        int         picupdatetime = BitConverter.ToInt32(data, 4);
                        //int thispicupdatetime = UserInfo.Select(user).PicUpdateTime;
                        int      thispicupdatetime = 0;
                        UserInfo userinfo          = UserInfo.Select(user);
                        if (userinfo != null)
                        {
                            thispicupdatetime = UserInfo.Select(user).PicUpdateTime;
                        }
                        if (thispicupdatetime > picupdatetime)
                        {
                            sendb.AddRange(BitConverter.GetBytes(thispicupdatetime));
                            sendb.AddRange(File.ReadAllBytes(tmp + "\\MSGer.tk\\pictures\\" + user + ".png"));
                        }
                        Networking.SendUpdate(Networking.UpdateType.GetImage, sendb.ToArray(), true); //2014.11.23.
                    }

                    /*else if (updatetype == Networking.UpdateType.CheckConn)
                     * { //2014.11.23.
                     *  Networking.SendUpdate(Networking.UpdateType.CheckConn, new byte[] { 0x01 }, true, new IPEndPoint(remoteEP.Address, port));
                     * }
                     * else if (updatetype == Networking.UpdateType.RequestConn)
                     * { //2014.11.23.
                     *  string[] s = Encoding.Unicode.GetString(data).Split(':');
                     *  var secondEP = new IPEndPoint(IPAddress.Parse(s[0]), Int32.Parse(s[1]));
                     *  Networking.SendUpdate(Networking.UpdateType.MakeConn, Encoding.Unicode.GetBytes(secondEP.ToString()), false, remoteEP); //Elküldi, hogy próbálkozzon kapcsolódni
                     *  Networking.SendUpdate(Networking.UpdateType.RequestConn, new byte[] { 0x01 }, true); //Majd válaszol, hogy ő is próbálkozhat
                     * }
                     * else if (updatetype == Networking.UpdateType.MakeConn)
                     * { //2014.11.23.
                     *  string[] s = Encoding.Unicode.GetString(data).Split(':');
                     *  var secondEP = new IPEndPoint(IPAddress.Parse(s[0]), Int32.Parse(s[1]));
                     *  Networking.SendUpdate(Networking.UpdateType.MakeConn2, new byte[] { 0x01 }, false, secondEP); //Próbálkoziks
                     *  Networking.SendUpdate(Networking.UpdateType.MakeConn, new byte[] { 0x01 }, true); //Válaszol, hogy ne várjon rá a szerver
                     * }
                     * else if (updatetype == Networking.UpdateType.MakeConn2)
                     * { //2014.11.23.
                     *  Networking.SendUpdate(Networking.UpdateType.MakeConn2, new byte[] { 0x01 }, true); //Végzett
                     * }*/
                } while (false);
            }
        }
Exemplo n.º 5
0
 private void SendLoginToUsers()
 { //2014.12.18.
     new Networking.PacketSender(new Networking.PDLoginUser(UserInfo.KnownUsers.Select(entry => new KeyValuePair <int, int>(entry.UserID, entry.LastUpdate))))
     .SendAsync().ContinueWith(new Action <Task <Networking.PacketFormat[]> >(
                                   (t) => Networking.ParseUpdateInfo(t.Result.Select(entry => ((Networking.PDLoginUser)entry.EData).RStrings))));
 }
Exemplo n.º 6
0
 private void sendbtn_Click(object sender, EventArgs e)
 {
     //TODO: Hibajelentés szerveroldalon
     Networking.SendRequest(Networking.RequestType.ErrorReport, textBox1.Text, 0, false); //2015.08.28.
 }