예제 #1
0
        public static async Task <SortedDictionary <string, decimal> > GetAllCurrencies(CancellationToken token = default(CancellationToken))
        {
            using (var client = new HttpClient())
            {
                string json       = null;
                var    currencies = new SortedDictionary <string, decimal>();
                try
                {
                    var response = await client.GetAsync(AllCurrenciesUrl, token);

                    response.EnsureSuccessStatusCode();
                    json = await response.Content.ReadAsStringAsync();

                    if (json == null)
                    {
                        throw new Exception();
                    }
                    var rawData   = JsonConverter.ConvertFromJson <Dictionary <string, object> >(json, false);
                    var list      = rawData["list"] as Dictionary <string, object>;
                    var resources = list["resources"] as ArrayList;
                    foreach (var resource in resources)
                    {
                        var content = ((Dictionary <string, object>)resource)["resource"] as Dictionary <string, object>;
                        if (content == null)
                        {
                            continue;
                        }
                        var fields = content["fields"] as Dictionary <string, object>;
                        if (fields == null)
                        {
                            continue;
                        }
                        object obj = null;
                        fields.TryGetValue("symbol", out obj);
                        if (obj == null)
                        {
                            continue;
                        }
                        string str = obj as string;
                        if (str == null)
                        {
                            continue;
                        }
                        var name = str.Split('=')[0];
                        if (name == "USD")
                        {
                            continue;
                        }
                        var price = Convert.ToDecimal((string)fields["price"], CultureInfo.InvariantCulture);
                        currencies[name] = price;
                    }
                }
                catch (Exception)
                {
                    return(null);
                }
                return(currencies.Count == 0 ? null : currencies);
            }
        }
예제 #2
0
        public static async Task <List <AlgoCoin> > GetWtmCoinNames(string coinType, CancellationToken token = default(CancellationToken))
        {
            string url = string.Empty;

            if (coinType == "GPU")
            {
                url = @"http://whattomine.com/coins.json";
            }
            if (coinType == "ASIC")
            {
                url = @"http://whattomine.com/asic.json";
            }

            string coinsJson = await WebDownloadAsync(url, false, token).ConfigureAwait(false);

            if (coinsJson == null)
            {
                return(null);
            }

            var dict = JsonConverter.ConvertFromJson <Dictionary <string, object> >(coinsJson) as Dictionary <string, object>;

            if (dict == null)
            {
                return(null);
            }
            object coinsOutput;

            dict.TryGetValue("coins", out coinsOutput);
            var coins = coinsOutput as Dictionary <string, object>;

            if (coins == null)
            {
                return(null);
            }
            var coinList = new List <AlgoCoin>();

            foreach (var coin in coins)
            {
                var property  = coin.Value as Dictionary <string, object>;
                var tag       = (string)property["tag"];
                var algorithm = (string)property["algorithm"];
                if (tag != "NICEHASH")
                {
                    coinList.Add(new AlgoCoin {
                        Name = coin.Key, Symbol = tag, Algorithm = algorithm
                    });
                }
            }
            coinList.OrderBy(x => x.Name);
            return(coinList);
        }
예제 #3
0
        public static WtmSettingsObject ReadWtmSettings(bool showError = true)
        {
            WtmSettingsObject settings          = null;
            WtmSettingsObject convertedSettings = null;
            string            settingsContent   = string.Empty;

            if (File.Exists(Constants.WtmSettingsFile))
            {
                try { settingsContent = File.ReadAllText(Constants.WtmSettingsFile); }
                catch { return(null); }
                convertedSettings = JsonConverter.ConvertFromJson <WtmSettingsObject>(settingsContent, showError);
                if (convertedSettings != null)
                {
                    settings = convertedSettings.Clone();
                }
            }
            return(settings);
        }
예제 #4
0
        //public static List<AlgoCoin> GetCoins(IList<Worker> workerList, bool checkForQuery = false, bool checkForSwitch = false)
        //{
        //    var coinList = new List<AlgoCoin>();
        //    foreach (Worker w in workerList)
        //    {
        //        if (checkForQuery && !w.Query)
        //            continue;

        //        foreach (CoinTable ct in w.CoinList)
        //        {
        //            if (checkForSwitch && !ct.Switch)
        //                continue;
        //            foreach (Coin c in ct.Coins)
        //                coinList.Add(new AlgoCoin(c.Name, c.Symbol, c.Algorithm));
        //        }
        //    }
        //    return coinList;
        //}

        public static Workers ReadWorkers(bool showError = true)
        {
            string  workersContent   = null;
            Workers convertedWorkers = null;

            try { workersContent = System.IO.File.ReadAllText(Constants.WorkersFile); }
            catch { return(null); }
            convertedWorkers = JsonConverter.ConvertFromJson <Workers>(workersContent, showError);
            if (convertedWorkers != null)
            {
                return(new Workers(
                           convertedWorkers.WorkerList,
                           convertedWorkers.PowerCost,
                           convertedWorkers.CoinType,
                           convertedWorkers.DisplayCoinAs,
                           convertedWorkers.NetworkScanMethod));
            }
            else
            {
                return(null);
            }
        }
예제 #5
0
        public static async Task <Dictionary <string, object> > GetAllCoinsJson(CancellationToken token = default(CancellationToken))
        {
            var coinsJson = await WebDownloadAsync(@"http://whattomine.com/calculators.json", false, token).ConfigureAwait(false);

            if (coinsJson == null)
            {
                return(null);
            }
            var coinsObj = JsonConverter.ConvertFromJson <Dictionary <string, object> >(coinsJson);

            if (coinsObj == null)
            {
                return(null);
            }
            var coins  = coinsObj["coins"] as Dictionary <string, object>;
            var result = new Dictionary <string, object>();

            foreach (var coin in coins)
            {
                string tag = (string)((Dictionary <string, object>)coin.Value)["tag"];
                result.Add(coin.Key, coin.Value);
            }
            return(result);
        }
예제 #6
0
        private async void ImportWorkersCommand(object parameter)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "JSON file|*.json";
            var openFileDialogResult = openFileDialog.ShowDialog();

            if (openFileDialogResult == false || string.IsNullOrEmpty(openFileDialog.FileName))
            {
                return;
            }

            string workersContent = null;
            ObservableCollection <Worker> convertedWorkers = null;

            try { workersContent = System.IO.File.ReadAllText(openFileDialog.FileName); }
            catch
            {
                await Task.Delay(100);

                MessageBox.Show($"There was an error while reading from \"{openFileDialog.FileName}\"", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            convertedWorkers = JsonConverter.ConvertFromJson <ObservableCollection <Worker> >(workersContent, false);
            if (convertedWorkers == null || convertedWorkers.Count == 0)
            {
                await Task.Delay(100);

                Helpers.ShowErrorMessage($"Failed to intepret JSON information from \"{openFileDialog.FileName}\"", "Error");
                return;
            }

            var window = new SelectWorkers();

            window.SizeToContent = SizeToContent.WidthAndHeight;
            var vm = new SelectWorkersVM();

            vm.Workers = convertedWorkers;
            foreach (var worker in vm.Workers)
            {
                worker.Query = true;
            }
            window.DataContext = vm;
            vm.Title           = "Import Workers";
            vm.ButtonTitle     = "Import";
            var dialogResult = window.ShowDialog();

            if (dialogResult == false)
            {
                return;
            }

            var selectedWorkers = vm.Workers.Where(x => x.Query).ToList();

            if (selectedWorkers == null || selectedWorkers.Count == 0)
            {
                return;
            }

            var workerIndex = Workers.WorkerList.IndexOf((Worker)parameter);

            Workers.WorkerListAddRangeAt(selectedWorkers, workerIndex);
        }
예제 #7
0
        public static async Task <(Dictionary <string, WtmData> data, GetWtmCoinDataResult result)> GetWtmCoinData(IDictionary <string, double> coinHashList, bool interactive, StreamWriter logFile = null)
        {
            string statusBarText = "Downloading coin definitions from whattomine.com";

            ViewModel.Instance.StatusBarText = statusBarText + "...";

            int i = 0; int cnt = coinHashList.Count;
            var wtmRequestIntervalOld = ViewModel.Instance.WtmSettings.WtmRequestInterval;

            if (cnt > ViewModel.Instance.WtmSettings.DynamicRequestTrigger)
            {
                ViewModel.Instance.BypassUndo(() => {
                    if (ViewModel.Instance.WtmSettings.WtmRequestInterval < ViewModel.Instance.WtmSettings.DynamicRequestInterval)
                    {
                        ViewModel.Instance.WtmSettings.WtmRequestInterval = ViewModel.Instance.WtmSettings.DynamicRequestInterval;
                    }
                });
            }

            bool errorFlag            = false;
            bool continueFlag         = false;
            bool exitEarly            = false;

            CancellationTokenSource cancelSource = new CancellationTokenSource();
            CancellationToken       token        = cancelSource.Token;
            ProgressManager         pm           = null;


            if (interactive)
            {
                pm = new ProgressManager("Accessing whattomine.com...", cancelSource);
                pm.SetIndeterminate(true);
                pm.SetProgressMaxValue(cnt);
            }

            await RespectTimeLimit();

            var wtmLinks = await WhatToMine.GetWtmLinksFromJson(token).ConfigureAwait(false);

            if (token.IsCancellationRequested)
            {
                pm?.Close();
                return(null, GetWtmCoinDataResult.Fail);
            }
            if (wtmLinks == null)
            {
                string errorMessage = "Failed to get the list of available coins from whattomine.com.";
                if (interactive)
                {
                    pm?.Close();
                    MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    if (logFile != null)
                    {
                        logFile.WriteLine(errorMessage);
                    }
                }
                return(null, GetWtmCoinDataResult.Fail);
            }
            if (interactive && pm != null)
            {
                pm.SetIndeterminate(false);
                pm.SetText("Downloading " + i + " of " + cnt);
                pm.SetProgressValue(0);
            }

            var    wtmDataDict                = new Dictionary <string, WtmData>();
            string currentJsonStr             = string.Empty;
            string currentCoinHtml            = string.Empty;
            GetWtmCoinDataResult methodResult = GetWtmCoinDataResult.OK;

            foreach (var coin in coinHashList)
            {
                continueFlag = false;
                List <string> httpResults = new List <string>();
                WtmLinks      entry;
                wtmLinks.TryGetValue(coin.Key, out entry);
                if (entry == null)
                {
                    string errorMessage = $"{coin.Key} has not been found among coins at http://whattomine.com/calculators. Execution aborted.";
                    errorFlag = true; methodResult = GetWtmCoinDataResult.CoinNotFound;
                    if (interactive)
                    {
                        Helpers.ShowErrorMessage(errorMessage);
                    }
                    else
                    {
                        if (logFile != null)
                        {
                            logFile.WriteLine(errorMessage);
                        }
                    }
                    break;
                }

                //Check whattomine coin status
                if (!string.Equals(entry.Status, "Active", StringComparison.InvariantCultureIgnoreCase))
                {
                    MessageBoxResult response = MessageBoxResult.OK;
                    string           message  = $"The status of {coin.Key} is reported as \"{entry.Status}\" by whattomine.com.";
                    if (interactive)
                    {
                        response = MessageBox.Show(message, "Coin is not active", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                    }
                    else
                    {
                        logFile.WriteLine(message);
                    }
                    if (interactive && response == MessageBoxResult.Cancel)
                    {
                        errorFlag = true;
                        break;
                    }
                    continue;
                }

                await RespectTimeLimit();

                try
                {
                    var response = await WtmHttpClient.GetAsync(entry.JsonLink + "?hr=" + coin.Value.ToString(CultureInfo.InvariantCulture), token).ConfigureAwait(false);

                    var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    if (result != null && result.Contains("errors"))
                    {
                        var wtmErrorDict = JsonConverter.ConvertFromJson <Dictionary <string, object> >(result);
                        if (wtmErrorDict != null)
                        {
                            object errorObj = null;
                            wtmErrorDict.TryGetValue("errors", out errorObj);
                            var errorList = errorObj as ArrayList;
                            if (errorList != null)
                            {
                                string errorMessage = string.Join(". ", errorList.ToArray());
                                if (errorMessage != null)
                                {
                                    throw new Exception(errorMessage);
                                }
                            }
                        }
                    }

                    response.EnsureSuccessStatusCode();
                    httpResults.Add(result);
                }
                catch (Exception e)
                {
                    if (interactive && e.Message == "A task was canceled.")
                    {
                        errorFlag = true; methodResult = GetWtmCoinDataResult.Fail;
                    }
                    else
                    {
                        string errorMessage = $"Failed to download {coin.Key} definition from whattomine.com.";
                        //continueFlag = true;
                        errorFlag    = true;
                        methodResult = GetWtmCoinDataResult.Fail;
                        if (interactive)
                        {
                            Helpers.ShowErrorMessage(errorMessage + "\n\n" + e.Message);
                        }
                        else
                        {
                            if (logFile != null)
                            {
                                logFile.WriteLine(errorMessage);
                            }
                        }
                    }
                }

                //if (continueFlag)
                //    continue;

                if (errorFlag || httpResults == null)
                {
                    break;
                }

                // Interpret JSON
                currentJsonStr = httpResults[0];
                Dictionary <string, string> json = new Dictionary <string, string>();
                json = JsonConverter.ConvertFromJson <Dictionary <string, string> >(currentJsonStr);

                if (json == null)
                {
                    string errorMessage = $"Failed to interpret {coin.Key} definition from whattomine.com.";
                    errorFlag = true; methodResult = GetWtmCoinDataResult.Fail;
                    if (interactive)
                    {
                        Helpers.ShowErrorMessage(errorMessage);
                    }
                    else
                    {
                        if (logFile != null)
                        {
                            logFile.WriteLine(errorMessage);
                        }
                    }
                    break;
                }
                else
                {
                    var defaultHashrate = coin.Value;
                    wtmDataDict.Add(coin.Key, new WtmData {
                        DefaultHashrate = defaultHashrate, Json = json
                    });
                }

                if (pm != null && !pm.IsAlive)
                {
                    exitEarly = true;
                    break;
                }

                i++;
                if (interactive && pm != null)
                {
                    pm.SetText("Downloaded " + i + " of " + cnt);
                    pm.SetProgressValue(i);
                }
                else
                {
                    ViewModel.Instance.StatusBarText = statusBarText + ": " + i + " of " + cnt;
                }
            }

            ViewModel.Instance.BypassUndo(() => ViewModel.Instance.WtmSettings.WtmRequestInterval = wtmRequestIntervalOld);
            ViewModel.Instance.UpdateNextJobStatus();

            if (!exitEarly && interactive)
            {
                pm?.Close();
            }
            if (errorFlag || exitEarly)
            {
                return(null, methodResult);
            }
            if (!interactive && (logFile != null))
            {
                var noun = wtmDataDict.Count == 1 ? "coin" : "coins";
                logFile.WriteLine($"The list of {wtmDataDict.Count} whattomine.com {noun} has been downloaded.");
            }
            return(wtmDataDict, GetWtmCoinDataResult.OK);
        }