Beispiel #1
0
        async void GET_recipeDto(string id)
        {
            try
            {
                HttpResponseMessage response = await httpClient.GetAsync(RamseyApi.V2.Recipe.Retreive + "?id=" + id);

                Analytics.TrackEvent("reciveRecipeResponse", new Dictionary <string, string> {
                    { "reciveRecipeResponseStatusCode", response.StatusCode.ToString() }
                });

                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();

                    recipe = JsonConvert.DeserializeObject <RecipeDtoV2>(result);
                    XamlSetup2();
                    loadedRecipe = true;
                }
                else
                {
                    await DisplayAlert("Fel", "Kunnde inte ansluta till servern\n\nstatus code: " + (int)response.StatusCode, "ok");
                }
            }
            catch (Exception ex)
            {
                Analytics.TrackEvent("reciveRecipe", new Dictionary <string, string> {
                    { "recipeID", id.ToString() }
                });

                Crashes.TrackError(ex);
                await DisplayAlert("Fel", "Kunnde inte ansluta till servern", "ok");
            }
        }
Beispiel #2
0
        public RecipePage(RecipeDtoV2 recipe)
        {
            InitializeComponent();
            BindingContext = this;

            fromSavedRecipes = true;
            this.recipe      = recipe;
            myIngredients    = User.User.SavedIngredinets;
            XamlSetup1();
            XamlSetup2();

            Task.Factory.StartNew(() => UpdateFavorite());
        }
        //Next page (favorite)
        async void GotoRecipePage(RecipeDtoV2 recipe)
        {
            await Navigation.PushAsync(new RecipePage(recipe) { Title = recipe.Name });

            canOpenNewRecipes = true;
        }
Beispiel #4
0
        public async Task <RecipeDtoV2> ScrapeRecipeAsync(string url, bool includeAll = false)
        {
            var stopWatch = new Stopwatch();

            stopWatch.Start();

            var recipe       = new RecipeDtoV2();
            var httpResponse = await _client.GetAsync(url);

            var html = await httpResponse.Content.ReadAsStringAsync();

            var document = new HtmlDocument();

            document.LoadHtml(html);

            recipe.Name = document.DocumentNode
                          .SelectSingleNode(Config.NameXPath)
                          .InnerText
                          .RemoveSpecialCharacters();

            if (Config.LoadImage != null)
            {
                recipe.Image = Config.LoadImage(document);
            }
            else
            {
                recipe.Image = document.DocumentNode
                               .SelectSingleNode(Config.ImageXPath)
                               .Attributes["src"]
                               .Value;
            }

            if (Config.ParseId != null)
            {
                recipe.RecipeId = Config.ParseId(url);
            }
            else
            {
                var id = url.ToString();
                recipe.RecipeId = Config.ProviderId + id.Remove(id.Count() - 1).Split('/').Last();
            }

            if (includeAll)
            {
                recipe.Directions = document.DocumentNode
                                    .SelectNodes(Config.DirectionsXPath)
                                    .Where(x => !x.InnerHtml.Contains("<strong>") || !x.InnerHtml.Contains("<th>"))
                                    .Select(x => WebUtility.HtmlDecode(x.InnerText))
                                    .Select(x => x.RemoveSpecialCharacters())
                                    .ToList();
            }

            recipe.Ingredients = document.DocumentNode
                                 .SelectNodes(Config.IngredientsXPath)
                                 .Select(x => WebUtility.HtmlDecode(x.InnerText))
                                 .Select(x => x.Replace("\t", ""))
                                 .Select(x => x.Replace("\n", string.Empty))
                                 .Select(x => x.Replace('.', ','))
                                 .Select(x => x.ToLower())
                                 .Select(x => x.Trim())
                                 .ToList();

            var ingRegex   = new Regex("([0-9]\\d*(\\,\\d+)? \\w+)");
            var quantRegex = new Regex("([0-9]\\d*(\\,\\d+)?)");

            var parts = new List <RecipePartDtoV2>();

            foreach (var ing in recipe.Ingredients)
            {
                var ingredient = ing;

                //Optional processing by provider
                if (Config.ProcessIngredient != null)
                {
                    ingredient = Config.ProcessIngredient(ingredient);
                }

                //Find quantity and unit
                var ingMatch = ingRegex.Match(ingredient);
                var amount   = ingMatch.Value;

                if (ingredient.Split(' ').Count() > 2 && amount != string.Empty)
                {
                    ingredient = ingredient.Replace(amount, string.Empty);
                }

                var quantityMatch = quantRegex.Match(amount);

                double.TryParse(quantityMatch.Value, out double quantity);

                string unit;
                if (quantityMatch.Success)
                {
                    unit = amount.Replace(quantityMatch.Value, string.Empty);
                }
                else
                {
                    unit = string.Empty;
                }

                //Remove illegal words
                //Find ingredient name
                string foundName = _illegalRemover.RemoveIllegals(ingredient);

                //Match the name
                var nameMatch = Regex.Matches(foundName, "([a-zåäöèîé]{3,})");

                if (nameMatch.Count > 0)
                {
                    //Find ingredient name
                    var sb      = new StringBuilder();
                    var matches = nameMatch.Where(x => x.Success).Select(x => x.Value);

                    foreach (var match in matches)
                    {
                        sb = sb.Append(" ").Append(match);
                    }

                    var actualName = sb.ToString().Trim();

                    parts.Add(new RecipePartDtoV2
                    {
                        IngredientName = actualName,
                        Quantity       = (float)quantity,
                        Unit           = unit.Trim(),
                    });
                }
                else
                {
                    //If pattern is not detected then skip it.
                    continue;
                }
            }

            recipe.RecipeParts = parts;

            recipe.OwnerLogo = Config.ProviderLogo;
            recipe.Source    = url.ToString();
            recipe.Owner     = Config.ProviderName;

            recipe.Tags = GetRecipeTags(document);

            stopWatch.Stop();

            Logger.Information("Recipe {0} took {1} ms to scrape.", recipe.Name, stopWatch.Elapsed.Milliseconds);

            return(recipe);
        }