Esempio n. 1
0
        public void Loader()
        {
            // AcceptTradeAction = AcceptTrades;
            //загрузка настроек
            if (!File.Exists("config.json"))
            {
                cfg = new Config();

                var mm = Enum.GetValues(typeof(MessageType));
                foreach (var it in mm)
                {
                    cfg.Messages.Add((MessageType)it, true);
                }
            }
            else
            {
                cfg = Config.Reload();
            }


            if (!String.IsNullOrEmpty(cfg.SteamLogin))
            {
                //если есть мобильный аутентификатор включаем автоматический прием вещей
                //если его нет, то узнаем, нужно ли забирать вещи самостоятельно
                if (File.Exists("account.maFile"))
                {
                    accountFileExist = true;
                }
                autoConfirmTrades = true;
                //else
                //{
                //    Console.WriteLine(("Автоматически получать вещи?"));
                //    var w = Console.ReadLine();
                //    if (w.ToLower() == "y")
                //    {
                //        tradeWorker.Auth();
                //        //Trades();
                //    }
                //}
            }
            else
            {
                Config.Save(cfg);

                Console.WriteLine("Заполните config.json для автоматического получения вещей");
            }

            tradeWorker = new TradeWorker();

            CallbackUpdater = new AsyncCallback(CorrectOrdersAndNotifications);
            if (cfg.MassUpdate)
            {
                UpdatePriceDelegateAction = MassUpdate;
            }
            else
            {
                UpdatePriceDelegateAction = CorrectPrice;
            }

            UpdateOrdersDelegate        = CorrectOrders;
            UpdateNotificationsDelegate = CorrectNotifications;
            QuickOrderAction            = QuickOrderF;
            CheckNotificationsDelegate  = CheckNotifications;

            CLIENT  = new functions();
            CLIENT1 = new functions();

            //загрузка итемов
            FileInfo b = new FileInfo("csgotmitems.dat");

            if (b.Exists)
            {
                FileStream      fstream         = File.Open("csgotmitems.dat", FileMode.Open);
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                Items = (List <Itm>)binaryFormatter.Deserialize(fstream);
                fstream.Close();
                Items.Sort(delegate(Itm i1, Itm i2) { return(i1.name.CompareTo(i2.name)); });
            }



            if (cfg.Messages.Count == 0 || cfg.Messages.Count != Enum.GetNames(typeof(MessageType)).Length)
            {
                var mm = Enum.GetValues(typeof(MessageType));
                foreach (var it in mm)
                {
                    try
                    {
                        cfg.Messages.Add((MessageType)it, true);
                    }
                    catch { }
                }

                Config.Save(cfg);
            }



            //таймер обновления цен
            UpdatePriceTimer.Elapsed += new ElapsedEventHandler(PriceCorrectTimer);
            UpdatePriceTimer.Interval = cfg.UpdatePriceTimerTime * 60 * 1000;

            pinPongTimer.Elapsed += new ElapsedEventHandler(PingPongTimer);
            pinPongTimer.Interval = cfg.PingPongTimerTime * 60 * 1000;

            client = new WebSocket(host);

            string id = "", answer = "";

            client.OnOpen += (ss, ee) =>
                             WriteMessage(string.Format("Подключение к {0} успешно ", host), MessageType.Info);

            client.OnError += (ss, ee) =>
            {
                //WriteMessage(string.Format("Ошибка: {0}\n{1}" + Environment.NewLine, ee.Message, ee.Exception), MessageType.Error);
            };

            var product     = new { type = "" };
            var invcache_go = new { data = new { time = "" } };
            var webnotify   = new { data = new { classid = "", instanceid = "", price = 0.0, way = "" } };
            var itemstatus4 = new { data = new { bid = "" } };
            var itemstatus  = new { data = new { status = "" } };
            var itemout     = new { data = new { ui_status = "" } };

            client.OnMessage += (ss, ee) =>
            {
                var type = JsonConvert.DeserializeAnonymousType(ee.Data, product);
                try
                {
                    switch (type.type)
                    {
                    case "webnotify":

                        /* answer = ee.Data.Replace("\\\"\",", "\\\",").Replace(@"\", "").Replace(" \"u0", "");
                         * answer = answer.Replace(":\"{", ":{").Replace("\"\"", "");
                         * answer = answer.Replace("}\"}", "}}");
                         * answer = answer.Replace("\\\"\",", "\\\",");*/
                        answer = ee.Data.Replace("\"\\\\u", "");
                        answer = answer.Replace("\\\\\\", "\\");
                        answer = answer.Replace("\\\"", "\"");
                        answer = answer.Replace(@"\""", "\"");
                        answer = answer.Replace(":\"\"{", ":{");
                        answer = answer.Replace("\"\",", "\",");
                        answer = answer.Replace("}\"\"}", "}}");

                        var ansWeb = JsonConvert.DeserializeAnonymousType(answer, webnotify);
                        //if (ansWeb != null && ansWeb.data.way == null)
                        //{
                        id = ansWeb.data.classid + "_" + ansWeb.data.instanceid;
                        var ItemInListWeb = Items.Find(item => item.id == id);     //&& item.price >= (t.data.ui_price));

                        if (ItemInListWeb != null && (CLIENT1.Buy(ItemInListWeb, cfg.key) || CLIENT1.Buy(ItemInListWeb, cfg.key, 100)))
                        {
                            WriteMessage(string.Format("*webnotify* {0} куплен за {1} ({2})", ItemInListWeb.name, ansWeb.data.price, ItemInListWeb.price), MessageType.BuyWeapon);
                        }
                        else
                        {
                            WriteMessage(string.Format("*webnotify* Не успел купить {0} выставлен за {1} ({2})", ItemInListWeb.name, ansWeb.data.price, ItemInListWeb.price), MessageType.Socket);
                        }

                        //}
                        break;

                    case "itemstatus_go":
                        //{"type":"itemstatus_go","data":"{\"id\":\"173474064\",\"status\":5}"}
                        //WriteMessage("itemstatus_go " + ee.Data);
                        answer = ee.Data.Replace("\\\"", "\"");
                        answer = answer.Replace(":\"{", ":{");
                        answer = answer.Replace("}\"}", "}}");
                        var itemstatus_go = new { data = new { status = "" } };
                        var ansItem       = JsonConvert.DeserializeObject <TrOf>(answer);
                        switch (ansItem.data.status)
                        {
                        case 4:
                            WriteMessage("Забрать вещи", MessageType.GetWeapon);
                            if (autoConfirmTrades)
                            {
                                tradeWorker.AcceptTrade(TypeTrade.OUT);
                            }
                            break;
                        }
                        break;

                    case "itemout_new_go":

#if DEBUG
                        System.Diagnostics.Debug.WriteLine(ee.Data);
#endif
                        //WriteMessage("itemout_new_go "+ee.Data);
                        answer = ee.Data.Replace("\\\"", "\"");
                        answer = answer.Replace(":\"{", ":{");
                        answer = answer.Replace("}\"}", "}}");
                        //answer = answer.Replace(":\"\"{", ":{");
                        //answer = answer.Replace("}\"\"}", "}}");
                        answer = answer.Replace(@"\", "");
                        var TemplItemout_new_go = new { data = new { ui_status = "" } };
                        var ans1 = JsonConvert.DeserializeAnonymousType(answer, TemplItemout_new_go);
                        switch (ans1.data.ui_status)
                        {
                        case "3":
                            WriteMessage("Передать вещи", MessageType.GiveWeapon);

                            tradeWorker.AcceptTrade(TypeTrade.IN);
                            break;
                        }

                        break;

                    //case "itemout_new_go":
                    //case "additem_go":
                    //case "invcache_go":
                    //case "invcache_gt":
                    //case "invcache_cs":
                    //case "invcache_tf":
                    //case "onlinecheck":
                    //case "setonline":
                    //case "money":
                    //case "webnotify_betsonly":
                    //    break;
                    case "newitems_go":
                        answer = ee.Data.Replace("\\\"", "\"");
                        answer = answer.Replace(":\"{", ":{");
                        answer = answer.Replace("}\"}", "}}");
                        answer = answer.Replace("\\\"\\\\u", "").Replace("\\\"\",", "\\\",");
                        WSItm t = JsonConvert.DeserializeObject <WSItm>(answer);

                        id = t.data.i_classid + "_" + t.data.i_instanceid;
                        var ItemInList = Items.Find(item => item.id == id);     //&& item.price >= (t.data.ui_price));

                        if (ItemInList != null && (ItemInList.price >= (t.data.ui_price)))
                        {
                            if (CLIENT1.Buy(ItemInList, cfg.key) || CLIENT1.Buy(ItemInList, cfg.key, 100))
                            {
                                WriteMessage(string.Format("*сокеты* {0} куплен за {1} ({2})", ItemInList.name, t.data.ui_price, ItemInList.price), MessageType.BuyWeapon);
                            }
                            else
                            {
                                WriteMessage(string.Format("*сокеты* Не успел купить {0} выставлен за {1} ({2})", ItemInList.name, t.data.ui_price, ItemInList.price), MessageType.Socket);
                            }
                        }
                        break;
                        //case "history_go":
                        //    /*answer = ee.Data.Replace(@"\", ""); ;
                        //    System.Text.RegularExpressions.Regex RID = new System.Text.RegularExpressions.Regex(@"\d+-\d+");
                        //    System.Text.RegularExpressions.Regex RPrice = new System.Text.RegularExpressions.Regex(@"\d+\.\d+");
                        //    if (RID.IsMatch(answer))
                        //    {
                        //        var Iid=RID.Match(answer);
                        //        var IPrice = RPrice.Match(answer);
                        //        var itm=Items.Find(item => item.id == Iid.Value);
                        //        if (itm!=null && Convert.ToDouble(IPrice)>itm.price)
                        //        {
                        //            CorrectPrice(itm);
                        //        }
                        //    }*/
                        //    break;
                        //                        default:
                        //#if DEBUG
                        //                            System.Diagnostics.Debug.WriteLine(ee.Data);
                        //#endif
                        //                            WriteMessage(string.Format("Сообщение: \n\r{0}", ee.Data));
                        //                            break;
                    }
                }
                catch (Exception e)
                {
#if DEBUG
                    System.Diagnostics.Debug.WriteLine(e.Message + Environment.NewLine + ee.Data);


                    if (type.type != "newitems_go" && type.type != "webnotify")
                    {
                        Console.WriteLine("Error " + type.type + " " + e.Message + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + answer + Environment.NewLine + Environment.NewLine);
                    }
#endif
                }
            };

            client.OnClose += (ss, ee) =>
            {
                WriteMessage(string.Format("Отключен от {0}", host), MessageType.Info);
                if (!Close)
                {
                    SocketsAuth();
                }
            };
        }