|
| 1 | +using System.Collections.Generic; |
| 2 | +using Microsoft.AspNetCore.Http; |
| 3 | +using Microsoft.Extensions.Primitives; |
| 4 | +using Microsoft.Net.Http.Headers; |
| 5 | +using Smidge; |
| 6 | +using Smidge.Models; |
| 7 | + |
| 8 | +namespace Umbraco.Cms.Web.Common.RuntimeMinification |
| 9 | +{ |
| 10 | + public class SmidgeRequestHelper : IRequestHelper |
| 11 | + { |
| 12 | + private RequestHelper _wrappedRequestHelper; |
| 13 | + |
| 14 | + public SmidgeRequestHelper(IWebsiteInfo siteInfo) |
| 15 | + { |
| 16 | + _wrappedRequestHelper = new RequestHelper(siteInfo); |
| 17 | + } |
| 18 | + |
| 19 | + /// <inheritdoc/> |
| 20 | + public string Content(string path) => _wrappedRequestHelper.Content(path); |
| 21 | + |
| 22 | + /// <inheritdoc/> |
| 23 | + public string Content(IWebFile file) => _wrappedRequestHelper.Content(file); |
| 24 | + |
| 25 | + /// <inheritdoc/> |
| 26 | + public bool IsExternalRequestPath(string path) => _wrappedRequestHelper.IsExternalRequestPath(path); |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Overrides the default order of compression from Smidge, since Brotli is super slow (~10 seconds for backoffice.js) |
| 30 | + /// </summary> |
| 31 | + /// <param name="headers"></param> |
| 32 | + /// <returns></returns> |
| 33 | + public CompressionType GetClientCompression(IDictionary<string, StringValues> headers) |
| 34 | + { |
| 35 | + var type = CompressionType.None; |
| 36 | + |
| 37 | + if (headers is not IHeaderDictionary headerDictionary) |
| 38 | + { |
| 39 | + headerDictionary = new HeaderDictionary(headers.Count); |
| 40 | + foreach ((var key, StringValues stringValues) in headers) |
| 41 | + { |
| 42 | + headerDictionary[key] = stringValues; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + var acceptEncoding = headerDictionary.GetCommaSeparatedValues(HeaderNames.AcceptEncoding); |
| 47 | + if (acceptEncoding.Length > 0) |
| 48 | + { |
| 49 | + // Prefer in order: GZip, Deflate, Brotli. |
| 50 | + for (var i = 0; i < acceptEncoding.Length; i++) |
| 51 | + { |
| 52 | + var encoding = acceptEncoding[i].Trim(); |
| 53 | + |
| 54 | + CompressionType parsed = CompressionType.Parse(encoding); |
| 55 | + |
| 56 | + // Not pack200-gzip. |
| 57 | + if (parsed == CompressionType.GZip) |
| 58 | + { |
| 59 | + return CompressionType.GZip; |
| 60 | + } |
| 61 | + |
| 62 | + if (parsed == CompressionType.Deflate) |
| 63 | + { |
| 64 | + type = CompressionType.Deflate; |
| 65 | + } |
| 66 | + |
| 67 | + // Brotli is typically last in the accept encoding header. |
| 68 | + if (type != CompressionType.Deflate && parsed == CompressionType.Brotli) |
| 69 | + { |
| 70 | + type = CompressionType.Brotli; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return type; |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments