RhSolutions-AddIn/Source/Assistant/SkuAssist.cs
Sergey Chebotar 8bc62a6f02 Refactoring
2021-12-05 21:25:30 +03:00

98 lines
2.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using AngleSharp.Dom;
using ExcelDna.Integration;
using Newtonsoft.Json;
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.Caching;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Rehau.Sku.Assist
{
public enum ProductField
{
Name,
Id,
Price
}
static class SkuAssist
{
public static async Task<IProduct> GetProduct(string request)
{
Uri uri = request.ConvertToUri();
Task<string> contentTask = Task.Run(() => HttpClientUtil.GetContentByUriAsync(uri));
Task<IDocument> documentTask = await contentTask.ContinueWith(content => HttpClientUtil.ContentToDocAsync(content));
return GetProduct(documentTask.Result);
}
public static IProduct GetProduct(IDocument document)
{
string script = document
.Scripts
.Where(s => s.InnerHtml.Contains("dataLayer"))
.First()
.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 => Regex.IsMatch(p.Id, @"\d{11}", RegexOptions.None))
.FirstOrDefault();
return product;
}
public static object GetProduct(string request, ProductField field)
{
IProduct product;
if (MemoryCache.Default.Contains(request))
{
product = MemoryCache.Default[request] as IProduct;
}
else
{
object result = ExcelAsyncUtil.Run("RauName", new[] { request },
delegate
{
Task<IProduct> p = Task.Run(() => GetProduct(request));
return p.Result;
});
if (result == null)
return "Не найдено :(";
if (result.Equals(ExcelError.ExcelErrorNA))
return "Загрузка...";
product = result as IProduct;
MemoryCache.Default.Add(request, product, DateTime.Now.AddMinutes(10));
}
switch (field)
{
case ProductField.Name:
return product.Name;
case ProductField.Id:
return product.Id;
case ProductField.Price:
return double.Parse((string)product.Price, CultureInfo.InvariantCulture);
default:
return ExcelError.ExcelErrorValue;
}
}
}
}