Example #1
0
 public YotaParser Clone()
 {
     var res = new YotaParser("");
     if (_html != null)
         res._html = _html;
     if (_productInfos != null)
     {
         res._productInfos = new ProductInfo[_productInfos.Length];
         for (int i = 0; i < _productInfos.Length; ++i)
             res._productInfos[i] = _productInfos[i].Clone();
         res._balance = _balance;
     }
     return res;
 }
Example #2
0
 public void OnSuccess(YotaParser parser)
 {
     _context.DisableReconnectOnError();
     if (_context._deviceId.Equals("") || !parser.DeviceIdExists(_context._deviceId))
     {
         _context._deviceId = parser.GetProductInfos()[0].deviceId;
         _context._yota.SetDeviceId(_context._deviceId);
         Settings.Default.DeviceID = _context._deviceId;
     }
     int rateNum = parser.GetCurrentRateNum(_context._deviceId);
     String days = parser.GetDays(_context._deviceId);
     String name = parser.GetShortRateName(_context._deviceId, rateNum);
     if (days == "0")
     {
         _context._animMgr.Stop("!");
         _context._notifyIcon.Text = "Не осталось оплаченных дней";
     }
     else
     {
         _context._animMgr.Stop(name);
         _context._notifyIcon.Text = parser.GetRateName(_context._deviceId, rateNum);
     }
     _context.UpdateContextMenu(parser);
     var fullName = parser.GetRateName(_context._deviceId, rateNum);
     if (_context._yota.GetLastRateNumber() == -1)
         Log.RateChecked(fullName);
     else
         Log.RateChanged(fullName);
 }
Example #3
0
        public static String GenShortRateNumber(YotaParser.RateInfo ri)
        {
            if (RateAliases.ContainsKey(ri.code))
                return RateAliases[ri.code];

            ri.speedNumber = ImproveSpeedNumber(ri.speedNumber).Substring(0, Math.Min(ri.speedNumber.Length, 4));

            if (ri.speedNumber.Contains("Макс"))
                return "M";

            // Если в Кбит/сек, то переводим в Мбит/сек с одним знаком после запятой.
            if (ri.speedString.Contains("Кбит"))
            {
                int buf;
                if (int.TryParse(ri.speedNumber, out buf))
                    return (buf / 1000.0).ToString("0.0", System.Globalization.CultureInfo.InvariantCulture);
                return ri.speedNumber;
            }

            // Отбрасываем значения после точек, если целая часть имеет 2 или более знаков.
            var ind = ri.speedNumber.IndexOf('.');
            if (ind == -1)
                ind = ri.speedNumber.Length - 1;
            if (ind == 1)
                ind += 2;
            return ri.speedNumber.Substring(0, ind);
        }
Example #4
0
 public void OnConnectionStart(int needRateNum, YotaParser parser)
 {
     String name = "?";
     if (needRateNum != -1)
     {
         if (parser == null)
             name = Scheduler.GetStartAppRateShortName();
         else name = parser.GetShortRateName(_context._deviceId, needRateNum);
         _context._animMgr.Start(name);
     }
     _context._animMgr.Start(name);
     _context.UpdateContextMenu(parser, false);
     _context._notifyIcon.Text = "Соединение...";
 }
Example #5
0
 public void UpdateContextMenu(YotaParser parser, bool needSelection = true)
 {
     _contextMenuStrip.Items.Clear();
     if (parser != null && parser.IsParsed() && parser.DeviceIdExists(_deviceId))
     {
         // баланс
         var balance = parser.GetBalance();
         if (balance != "")
         {
             _contextMenuStrip.Items.Add("Баланс: " + balance);
             _contextMenuStrip.Items[_contextMenuStrip.Items.Count - 1].Tag = KeyBalance;
             _contextMenuStrip.Items.Add("-");
         }
         // тарифы
         int count = parser.GetRateCount(_deviceId);
         int current = parser.GetCurrentRateNum(_deviceId);
         for (int i = 0; i < count; ++i)
         {
             String code = parser.GetRateCode(_deviceId, i);
             if (Array.IndexOf(_excludeRatesCodes, code) == -1)
             {
                 String name = parser.GetRateName(_deviceId, i);
                 _contextMenuStrip.Items.Add(name);
                 _contextMenuStrip.Items[_contextMenuStrip.Items.Count - 1].Tag = i;
                 if (i == current && needSelection)
                     (_contextMenuStrip.Items[_contextMenuStrip.Items.Count - 1] as ToolStripMenuItem).Checked =
                         true;
             }
         }
         _contextMenuStrip.Items.Add("-");
     }
     var yet = new ToolStripMenuItem("Другое");
     yet.Tag = KeyOther;
     yet.DropDownItemClicked += OnItemClick;
     _contextMenuStrip.Items.Add(yet);
     var exit = new ToolStripMenuItem("Выход");
     exit.Tag = KeyExit;
     _contextMenuStrip.Items.Add(exit);
     if (_scheduler != null && _scheduler.NeedChangeOnEvent(Scheduler.KeyOnExitApp))
     {
         exit.DropDownItemClicked += OnItemClick;
         var directExit = new ToolStripMenuItem("Выход без изменения скорости");
         directExit.Tag = KeyDirectExit;
         exit.DropDownItems.Add(directExit);
     }
     // другое
     if (parser != null && _scheduler != null)
     {
         var schedule = new ToolStripMenuItem("Планировщик");
         schedule.Tag = KeySchedule;
         yet.DropDownItems.Add(schedule);
     }
     if (_needLog)
     {
         var log = new ToolStripMenuItem("Журнал");
         log.Tag = KeyLog;
         yet.DropDownItems.Add(log);
     }
     var settings = new ToolStripMenuItem("Настройки");
     settings.Tag = KeySettings;
     yet.DropDownItems.Add(settings);
     if (parser != null)
     {
         var device = new ToolStripMenuItem("Устройство");
         device.Tag = KeyDevice;
         device.DropDownItemClicked += OnDeviceChange;
         yet.DropDownItems.Add(device);
         String[] deviceIds = parser.GetProductInfos().Select(pi => pi.deviceId).ToArray();
         foreach (var deviceId in deviceIds)
         {
             var nextDeviceItem = new ToolStripMenuItem(parser.GetDeviceName(deviceId));
             nextDeviceItem.Tag = deviceId;
             if (deviceId == _deviceId)
                 nextDeviceItem.Checked = true;
             device.DropDownItems.Add(nextDeviceItem);
         }
     }
     var about = new ToolStripMenuItem("О программе");
     about.Tag = KeyAbout;
     yet.DropDownItems.Add(about);
 }
Example #6
0
 private void _setRate(int needRateNum)
 {
     if (_parser.GetCurrentRateNum(_deviceId) != needRateNum)
     {
         if (!_successAuth)
             throw new Exception("Сначала необходимо пройти аутентификацию");
         var reqFormData = new Dictionary<String, String>();
         String productId = _parser.GetProductId(_deviceId);
         reqFormData["product"] = productId;
         reqFormData["offerCode"] = _parser.GetRateCode(_deviceId, needRateNum);
         reqFormData["status"] = "custom";
         if (!_request(UrlRateChanger, MethodPost, reqFormData, UrlDevicesPages))
             throw new Exception("Не удалось подключиться к серверу");
         var parserBuf = new YotaParser(_responseData);
         if (parserBuf.GetCurrentRateNum(_deviceId) != needRateNum)
             throw new Exception("Не удалось изменить тариф");
         _parser = parserBuf;
     }
 }
Example #7
0
 private void _authentication()
 {
     _successAuth = false;
     if (_useDirectReference)
         _successAuth = _authenticationRequestWithoutLogin();
     if (!_successAuth)
     {
         if (!_useDirectReference && (_login.Equals("") || _password.Equals("")))
             throw new Exception("Введите логин и пароль");
         _successAuth = _authenticationRequestByLogin();
         if (_currentLocation != null && _currentLocation.Contains("login") && _currentLocation.Contains("error"))
             throw new Exception("Неправильный логин или пароль");
         if (_currentLocation != null && _currentLocation.Contains("error-selfcare"))
             throw new Exception("Личный кабинет не доступен");
     }
     if (!_successAuth)
         throw new Exception("Не удалось войти в личный кабинет");
     _parser = new YotaParser(_responseData);
     if (!_parser.IsParsed())
         throw new Exception("Не удалось обработать данные личного кабинета");
     if (_parser.GetProductCount() == 0)
         throw new Exception("Нет подключенных устройств");
 }
Example #8
0
        public SettingsView(AppContext context, YotaParser parser = null)
        {
            InitializeComponent();
            _context = context;

            if (parser != null && parser.IsParsed())
                _parser = parser;
            else
                _parser = null;

            // Логин.
            loginTextEdit.Text = _startLogin = Settings.Default.Login;

            // Пароль.
            passwordTextEdit.Text = _startPassword = Settings.Default.Password;

            // Подключаться без ввода логина и пароля (при подключении через устройство от Yota).
            useDirectReferenceCheckBox.Checked = _startUseDirectRef = Settings.Default.UseDirectReference;

            // Писать журнал событий в файл.
            logCheckBox.Checked = _startNeedLog = Settings.Default.NeedLog;
            logPathButton.Enabled = logPathLabel.Enabled = logCheckBox.Checked;

            // Путь к журналу.
            string logPath = Settings.Default.LogPath;
            if (logPath == "")
            {
                logPath = Environment.CurrentDirectory;
                if (!Log.IsDirectoryWritable(logPath))
                    logPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }
            logPathButton.Text = logPath;

            // Список отображаемых тарифов.
            var ratesUnknown = true;
            if (_parser != null){
                String deviceId = Settings.Default.DeviceID;
                if (_parser.DeviceIdExists(deviceId))
                {
                    ratesUnknown = false;
                    _excludeRates = Settings.Default.ExcludedRates.Split(';');
                    int rateCount = _parser.GetRateCount(deviceId);
                    for (int i = 0; i < rateCount; ++i)
                    {
                        var newRow = (DataGridViewRow) ratesDataGridView.RowTemplate.Clone();
                        newRow.CreateCells(ratesDataGridView);

                        // код тарифа
                        newRow.Tag = _parser.GetRateCode(deviceId, i);
                        // отображаем или нет тариф
                        newRow.Cells[0].Value = Array.IndexOf(_excludeRates, (String) newRow.Tag) == -1;
                        // название тарифа
                        newRow.Cells[1].Value = _parser.GetMiddleRateName(deviceId, i);
                        // сокращенное название
                        newRow.Cells[2].Value = _parser.GetShortRateName(deviceId, i);

                        ratesDataGridView.Rows.Add(newRow);
                    }
                }
            }

            // Видимость элементов интерфейса, задающих список отображаемых тарифов
            shownLabel.Visible = !ratesUnknown;
            ratesDataGridView.Visible = !ratesUnknown;
            noParserLabel.Visible = ratesUnknown;

            // Автозапуск при старте Windows.
            autoStartCheckBox.Checked = rkApp.GetValue(AppName) != null;

            // Планировщик.
            planCheckBox.Checked = Settings.Default.NeedScheduler;

            // Цвет фона.
            backColorButton.BackColor = _backColor = Settings.Default.BackgroundColor;

            // Цвет текста.
            textColorButton.BackColor = _textColor = Settings.Default.TextColor;

            // Прозрачный фон.
            transpBackColorCheckBox.Checked = _backColor.A == Color.Transparent.A;
            backLabel.Enabled = backColorButton.Enabled = !transpBackColorCheckBox.Checked;

            // Шрифт текста.
            fontButton.Font = _textFont = Settings.Default.TextFont;
        }