StyleSheetRequestProcessor
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using AngleSharp.Extensions;
using AngleSharp.Services;
using AngleSharp.Services.Styling;
using System.Threading;
using System.Threading.Tasks;
namespace AngleSharp.Network.RequestProcessors
{
internal sealed class StyleSheetRequestProcessor : BaseRequestProcessor
{
private readonly HtmlLinkElement _link;
private readonly Document _document;
private readonly IResourceLoader _loader;
private IStyleEngine _engine;
public IStyleSheet Sheet { get; set; }
public IStyleEngine Engine => _engine ?? (_engine = _document.Options.GetStyleEngine(LinkType));
public string LinkType => _link.Type ?? MimeTypeNames.Css;
private StyleSheetRequestProcessor(HtmlLinkElement link, Document document, IResourceLoader loader)
: base(loader)
{
_link = link;
_document = document;
_loader = loader;
}
internal static StyleSheetRequestProcessor Create(HtmlLinkElement element)
{
Document owner = element.Owner;
IResourceLoader loader = owner.Loader;
if (loader == null)
return null;
return new StyleSheetRequestProcessor(element, owner, loader);
}
public override Task ProcessAsync(ResourceRequest request)
{
if (Engine != null && IsDifferentToCurrentDownloadUrl(request.Target)) {
CancelDownload();
base.Download = DownloadWithCors(request);
return FinishDownloadAsync();
}
return null;
}
protected override async Task ProcessResponseAsync(IResponse response)
{
CancellationToken none = CancellationToken.None;
StyleOptions options = new StyleOptions(_document.Context) {
Element = _link,
IsDisabled = _link.IsDisabled,
IsAlternate = _link.RelationList.Contains(Keywords.Alternate)
};
IStyleSheet styleSheet = await _engine.ParseStylesheetAsync(response, options, none).ConfigureAwait(false);
styleSheet.Media.MediaText = (_link.Media ?? string.Empty);
Sheet = styleSheet;
}
private IDownload DownloadWithCors(ResourceRequest request)
{
return _loader.FetchWithCors(new CorsRequest(request) {
Setting = _link.CrossOrigin.ToEnum(CorsSetting.None),
Behavior = OriginBehavior.Taint,
Integrity = _document.Options.GetProvider<IIntegrityProvider>()
});
}
}
}