RhSolutions-AddIn/Source/Assistant/SkuAssist.cs

105 lines
3.0 KiB
C#
Raw Normal View History

using AngleSharp.Dom;
2021-12-03 22:25:20 +03:00
using ExcelDna.Integration;
2021-12-03 19:30:35 +03:00
using Newtonsoft.Json;
2021-11-29 21:24:44 +03:00
using System;
using System.Linq;
2021-12-03 22:25:20 +03:00
using System.Runtime.Caching;
using System.Text.RegularExpressions;
2021-12-03 19:30:35 +03:00
using System.Threading.Tasks;
2021-11-29 21:24:44 +03:00
namespace Rehau.Sku.Assist
{
public enum ResponseOrder
{
NoSettings,
Relevance,
Name,
Price,
Series
}
2021-12-03 22:25:20 +03:00
public enum ProductField
{
Name,
Id,
Price
}
2021-11-29 21:24:44 +03:00
static class SkuAssist
{
public static async Task<IProduct> GetProduct(string request)
2021-11-29 21:24:44 +03:00
{
Uri uri = request.ConvertToUri(ResponseOrder.NoSettings);
2021-11-29 21:24:44 +03:00
Task<string> contentTask = Task.Run(() => HttpClientUtil.GetContentByUriAsync(uri));
Task<IDocument> documentTask = await contentTask.ContinueWith(content => HttpClientUtil.ContentToDocAsync(content));
2021-11-29 21:24:44 +03:00
2021-12-03 19:30:35 +03:00
return GetProduct(documentTask.Result);
2021-11-29 21:24:44 +03:00
}
2021-12-03 19:30:35 +03:00
public static IProduct GetProduct(IDocument d)
2021-11-29 21:24:44 +03:00
{
2021-12-03 19:30:35 +03:00
string script = d.Scripts
.Where(s => s.InnerHtml.Contains("dataLayer"))
.First()
.InnerHtml;
2021-11-29 21:24:44 +03:00
2021-12-03 19:30:35 +03:00
string json = script
.Substring(script.IndexOf("push(") + 5)
.TrimEnd(new[] { ')', ';', '\n', ' ' });
2021-12-05 15:35:43 +03:00
if (!json.Contains("impressions"))
return null;
2021-12-03 19:30:35 +03:00
StoreResponce storeResponse = JsonConvert.DeserializeObject<StoreResponce>(json);
IProduct product = storeResponse
.Ecommerce
.Impressions
2021-12-03 22:25:20 +03:00
.Where(p => Regex.IsMatch(p.Id, @"\d{11}", RegexOptions.None))
.FirstOrDefault();
2021-12-03 19:30:35 +03:00
return product;
2021-11-29 21:24:44 +03:00
}
2021-12-03 22:25:20 +03:00
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 product.Price;
default:
return ExcelError.ExcelErrorValue;
}
}
2021-11-29 21:24:44 +03:00
}
}