示例#1
0
        public MagicBinderCardViewModel(
            IMagicCardDefinition definition,
            MagicBinderCard card)
        {
            _notificationCenter = NotificationCenter.Instance;
            _definition         = definition;
            _card  = card;
            _price = StaticPriceDatabase.FindPrice(_definition, false, false, "", false);
            _price.PriceChanged += OnPricePriceChanged;

            UpdatePrice();
        }
        public static void OnImageChanged(
            DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            var instance = d as CardImage;

            if (instance != null)
            {
                instance.imageControl.Source = instance._emptyImage;

                // Trigger download and display
                var card = instance.SelectedCard;

                instance.SetDefinition = card != null
                    ? StaticMagicData.SetDefinitionsBySetCode[card.SetCode]
                    : null;

                MagicCardPrice cardPrice    = null;
                var            cardFileName = string.Empty;
                Task.Factory.StartNew(() =>
                {
                    cardPrice = StaticPriceDatabase.FindPrice(card, false, false, "CardImage control", false);

                    var download = new CardImageDownload(instance._notificationCenter);
                    cardFileName = download.DownloadImage(card, cardPrice);
                }).ContinueWith(task =>
                {
                    // Lookup card price:
                    instance.CardPrice = cardPrice;

                    if (string.IsNullOrWhiteSpace(cardFileName))
                    {
                        instance.imageControl.Source = instance._emptyImage;
                    }
                    else
                    {
                        var uri    = new Uri(cardFileName);
                        var bitmap = new BitmapImage(uri);
                        bitmap.Freeze();
                        instance.imageControl.Source = bitmap;
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());
            }
        }
        private void RequestActualVendorPrice(
            string mkmId,
            string cardName,
            MagicCardPrice cardPrice,
            string additionalLogText)
        {
            if (string.IsNullOrWhiteSpace(mkmId))
            {
                return;
            }

            List <MkmSellerArticleData> allSellerData = new List <MkmSellerArticleData>();
            var maxLoops = 1;
            var maxExtraLoopsForMissingFoil = 1;

            var helper     = new RequestHelper(_notificationCenter, additionalLogText);
            var startIndex = 1;

            do
            {
                _notificationCenter.FireNotification(
                    LogLevel.Debug,
                    string.Format("Requesting seller data for {0} ({2}) at index {1}... ", mkmId, startIndex, cardName) + additionalLogText);

                if (!CheckRequestCount(false, true))
                {
                    maxLoops = 0;
                    continue;
                }

                WorkaroundTimeout(_notificationCenter, additionalLogText);
                var resultSpecialLogic = helper.MakeRequest(RequestHelper.CreateGetArticlesUrl(
                                                                mkmId,
                                                                MagicLanguage.English,
                                                                true,
                                                                startIndex));

                var countries  = new[] { "D", };
                var conditions = new[] { "NM", "M" };
                var languages  = new[] { "German", "English" };

                var foundSellers = AnalyseMkmSellerRequestResult
                                   .Analyse(
                    resultSpecialLogic.Response,
                    countries,
                    conditions,
                    languages)
                                   .OrderBy(s => s.Price)
                                   .ToList();

                allSellerData = allSellerData.Union(foundSellers).ToList();

                if (resultSpecialLogic.HttpResponse.StatusCode == System.Net.HttpStatusCode.PartialContent)
                {
                    startIndex += 100;
                    maxLoops   -= 1;

                    if (maxExtraLoopsForMissingFoil == 0)
                    {
                        var foundFoilSeller = allSellerData.FirstOrDefault(s => s.IsFoil == true);
                        if (foundFoilSeller != null)
                        {
                            // Found a foil -> Abort
                            maxLoops = 0;
                        }
                    }

                    if (maxLoops == 0)
                    {
                        var foundFoilSeller = allSellerData.FirstOrDefault(s => s.IsFoil == true);
                        maxLoops = foundFoilSeller == null ? maxExtraLoopsForMissingFoil : 0;

                        maxExtraLoopsForMissingFoil = 0;
                    }
                }
                else
                {
                    maxLoops = 0;
                }
            }while (maxLoops > 0);

            var seller     = allSellerData.FirstOrDefault(s => s.IsFoil == false);
            var sellerFoil = allSellerData.FirstOrDefault(s => s.IsFoil == true);

            cardPrice.CheapestPrice     = seller != null ? seller.Price : (decimal?)null;
            cardPrice.CheapestPriceFoil = sellerFoil != null ? sellerFoil.Price : (decimal?)null;

            cardPrice.CheapestSeller     = seller != null ? seller.SellerName : null;
            cardPrice.CheapestSellerFoil = sellerFoil != null ? sellerFoil.SellerName : null;

            _notificationCenter.FireNotification(
                LogLevel.Debug,
                string.Format(
                    "Downloading seller price data for '{0} ({6})' found {1} sellers. Cheapest = {2} ({3}), Foil = {4} ({5}) ",
                    mkmId,
                    allSellerData.Count(),
                    seller != null ? seller.SellerName : "<none>",
                    seller != null ? seller.Price : 0.00m,
                    sellerFoil != null ? sellerFoil.SellerName : "<none>",
                    sellerFoil != null ? sellerFoil.Price : 0.00m,
                    cardName) + additionalLogText);
        }
        public string DownloadImage(MagicCardDefinition card, MagicCardPrice cardPrice)
        {
            if (card == null)
            {
                return(null);
            }

            if (cardPrice == null)
            {
                cardPrice = StaticPriceDatabase.FindPrice(card, false, false, "CardImage download", false);
            }

            // Add default image path if needed
            cardPrice.BuildDefaultMkmImagePath(card);

            FileInfo localStorage = null;
            string   fullUrl      = null;

            try
            {
                var cache = PathHelper.CardImageCacheFolder;
                localStorage = new FileInfo(Path.Combine(cache, CreateCardIdPart(card, '\\', true, true).TrimStart('\\')));
                if (localStorage.Exists)
                {
                    return(localStorage.FullName);
                }

                var url = CreateCardIdPart(card, '/', false, false);
                if (url == null)
                {
                    return(null);
                }

                var stopwatch = Stopwatch.StartNew();

                if (!localStorage.Directory.Exists)
                {
                    localStorage.Directory.Create();
                }

                using (var client = new WebClient())
                {
                    var rootUrl = card.MagicCardType != MagicCardType.Token
                        ? "http://magiccards.info/scans/en"
                        : "http://magiccards.info/extras/token";

                    fullUrl = !string.IsNullOrWhiteSpace(cardPrice.ImagePath)
                        ? "http://www.magickartenmarkt.de/" + cardPrice.ImagePath
                        : rootUrl + url;

                    client.DownloadFile(new Uri(fullUrl), localStorage.FullName);
                }

                stopwatch.Stop();
                _notificationCenter.FireNotification(
                    LogLevel.Debug,
                    string.Format("Downloaded image for '{0}[{1}]' in {2}", card.NameEN, card.SetCode, stopwatch.Elapsed));
            }
            catch (Exception error)
            {
                _notificationCenter.FireNotification(
                    LogLevel.Debug,
                    string.Format("Error downloading image for '{0}[{1}]': {2} ({3})", card.NameEN, card.SetCode, error.Message, fullUrl));

                return(null);
            }

            return(localStorage.FullName);
        }
        public void PerformRequest(
            IMagicCardDefinition card,
            MagicCardPrice cardPrice,
            bool notifyOfPriceUpdate,
            string additionalLogText)
        {
            try
            {
                var foundSet      = false;
                var setDefinition = StaticMagicData.SetDefinitionsBySetCode[card.SetCode];

                var setName = setDefinition.Name;
                switch (setName)
                {
                case "Time Spiral \"Timeshifted\"":
                    setName = "Time Spiral";
                    break;

                case "Friday Night Magic":
                    setName = "Friday Night Magic Promos";
                    break;

                case "Magic 2014 Core Set":
                    setName = "Magic 2014";
                    break;

                case "Magic 2015 Core Set":
                    setName = "Magic 2015";
                    break;
                }

                var cardName = card.NameEN;

                var cardNameMkm = string.IsNullOrWhiteSpace(card.NameMkm)
                    ? card.NameEN
                    : card.NameMkm;

                if (!CheckRequestCount(false, true))
                {
                    return;
                }

                WorkaroundTimeout(_notificationCenter, additionalLogText);
                var helper = new RequestHelper(_notificationCenter, additionalLogText);
                using (var result = helper.MakeRequest(RequestHelper.CreateGetProductsUrl(cardName, MagicLanguage.English, card.MagicCardType != MagicCardType.Token, null)))
                {
                    var productNodes = result.Response.Root.Elements("product");
                    foreach (var productNode in productNodes)
                    {
                        var exactNameMatch = false;

                        var expansion = productNode.Element("expansion");
                        if (expansion == null || !expansion.Value.Equals(setName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            continue;
                        }

                        // Lookup correct version:
                        var nameNodes = productNode.Elements("name");
                        foreach (var nameNode in nameNodes)
                        {
                            var idLanguage = nameNode.Element("idLanguage");
                            if (idLanguage != null && idLanguage.Value == "1")
                            {
                                var exactProductName = nameNode.Element("productName");
                                if (exactProductName != null && exactProductName.Value.Equals(cardNameMkm, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    // Exact name matches.
                                    exactNameMatch = true;
                                    break;
                                }
                            }
                        }

                        if (!exactNameMatch)
                        {
                            continue;
                        }

                        foundSet = true;
                        var priceGuide = productNode.Element("priceGuide");
                        if (priceGuide != null)
                        {
                            cardPrice.IsNotifying = false;
                            try
                            {
                                cardPrice.PriceLow     = decimal.Parse(priceGuide.Element("LOW").Value, CultureInfo.InvariantCulture);
                                cardPrice.PriceAvg     = decimal.Parse(priceGuide.Element("AVG").Value, CultureInfo.InvariantCulture);
                                cardPrice.PriceFoilLow = decimal.Parse(priceGuide.Element("LOWFOIL").Value, CultureInfo.InvariantCulture);
                                cardPrice.PriceTrend   = decimal.Parse(priceGuide.Element("TREND").Value, CultureInfo.InvariantCulture);
                                cardPrice.PriceSell    = decimal.Parse(priceGuide.Element("SELL").Value, CultureInfo.InvariantCulture);

                                cardPrice.ImagePath = productNode.Element("image").Value;
                                cardPrice.WebSite   = productNode.Element("website").Value;

                                // Get lowest actual price from german vendor
                                var mkmId = productNode.Element("idProduct");
                                if (mkmId != null)
                                {
                                    cardPrice.MkmId = mkmId.Value;
                                    RequestActualVendorPrice(mkmId.Value, card.NameEN, cardPrice, additionalLogText);
                                }
                            }
                            finally
                            {
                                cardPrice.IsNotifying = true;
                            }
                        }

                        cardPrice.UpdateUtc = DateTime.UtcNow;
                        _notificationCenter.FireNotification(
                            LogLevel.Debug,
                            string.Format("Downloaded price data for '{0}({1})': {2}/{3}/{4}/'{5}'", card.DisplayNameEn, card.SetCode, cardPrice.PriceLow, cardPrice.PriceAvg, cardPrice.PriceTrend, cardPrice.ImagePath) + additionalLogText);

                        // Found my price -> Can exit loop now
                        break;
                    }

                    if (!foundSet)
                    {
                        _notificationCenter.FireNotification(
                            LogLevel.Debug,
                            string.Format("Cannot find price data for '{0}({1})'. Request: {2}", card.DisplayNameEn, setDefinition.Name, result.Response.Root) + additionalLogText);
                    }

                    if (notifyOfPriceUpdate)
                    {
                        cardPrice.RaisePriceChanged();
                        RequestCounter.Save();
                    }
                }
            }
            catch (Exception error)
            {
                if (notifyOfPriceUpdate)
                {
                    RequestCounter.Save();
                }

                _notificationCenter.FireNotification(
                    LogLevel.Error,
                    string.Format("Error downloading price data for '{0}({1})': {2}", card.DisplayNameEn, card.SetCode, error.Message) + additionalLogText);
            }
        }