RhSolutions-AddIn/Source/Assistant/SkuAssist.cs

62 lines
2.0 KiB
C#
Raw Normal View History

using AngleSharp.Dom;
using AngleSharp.Html.Dom;
2021-11-29 21:24:44 +03:00
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
2021-11-29 21:24:44 +03:00
namespace Rehau.Sku.Assist
{
public enum ResponseOrder
{
NoSettings,
Relevance,
Name,
Price,
Series
}
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
IProduct product = await documentTask.ContinueWith(doc => SkuAssist.GetFirstProduct(doc.Result));
return product;
2021-11-29 21:24:44 +03:00
}
public static IProduct GetFirstProduct(IDocument doc)
2021-11-29 21:24:44 +03:00
{
return doc
2021-11-29 21:24:44 +03:00
.All
.Where(e => e.ClassName == "product-item__desc-top")
.Where(e => Regex.IsMatch(e.Children[0].TextContent, @"\d{11}", RegexOptions.None))
.Select(e =>
new Product(e.Children[0].TextContent,
e.Children[1].TextContent.Trim(new[] { '\n', ' ' })))
2021-11-29 21:24:44 +03:00
.FirstOrDefault();
}
public static Uri GetFirstResultLink(IDocument doc)
2021-11-29 21:24:44 +03:00
{
var link = new Uri(doc
.Links
.Where(e => e.ClassName == "product-item__title-link js-name")
.Select(l => ((IHtmlAnchorElement)l).Href)
.FirstOrDefault());
return link;
2021-11-29 21:24:44 +03:00
}
public static string GetFistResultImageLink(IDocument doc)
2021-11-29 21:24:44 +03:00
{
var imageSource = doc.Images
.Where(x => x.ClassName == "product-item__image")
.FirstOrDefault();
return imageSource != null ? imageSource.Source : "Нет ссылки";
2021-11-29 21:24:44 +03:00
}
}
}