aboutsummaryrefslogtreecommitdiff
path: root/Source/Assistant/ParseUtil.cs
blob: 571c6b02df22906744c9783b09da8ee6ba648d00 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using AngleSharp;
using AngleSharp.Dom;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RehauSku.Assistant
{
    static class ParseUtil
    {
        public async static Task<IDocument> ContentToDocAsync(string content)
        {
            IConfiguration config = Configuration.Default;
            IBrowsingContext context = BrowsingContext.New(config);

            return await context.OpenAsync(req => req.Content(content));
        }

        public static IProduct GetProduct(IDocument document)
        {
            try
            {
                string script = document
                    .Scripts
                    .Where(s => s.InnerHtml.Contains("dataLayer"))
                    .FirstOrDefault()
                    .InnerHtml;

                string json = script
                    .Substring(script.IndexOf("push(") + 5)
                    .TrimEnd(new[] { ')', ';', '\n', ' ' });

                if (!json.Contains("impressions"))
                    return null;

                StoreResponce storeResponse = JsonConvert.DeserializeObject<StoreResponce>(json);
                IProduct product = storeResponse
                    .Ecommerce
                    .Impressions
                    .Where(p => p.Id.IsRehauSku())
                    .FirstOrDefault();

                return product;
            }

            catch (NullReferenceException e)
            {
                MessageBox.Show(e.Message, "Ошибка получения данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
    }
}