HttpResultFactory.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.IO.Compression;
  6. using System.Net;
  7. using System.Runtime.Serialization;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Xml;
  12. using Emby.Server.Implementations.Services;
  13. using MediaBrowser.Common.Extensions;
  14. using MediaBrowser.Controller.Net;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.Serialization;
  17. using MediaBrowser.Model.Services;
  18. using Microsoft.Extensions.Logging;
  19. using IRequest = MediaBrowser.Model.Services.IRequest;
  20. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  21. namespace Emby.Server.Implementations.HttpServer
  22. {
  23. /// <summary>
  24. /// Class HttpResultFactory
  25. /// </summary>
  26. public class HttpResultFactory : IHttpResultFactory
  27. {
  28. /// <summary>
  29. /// The _logger
  30. /// </summary>
  31. private readonly ILogger _logger;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly IJsonSerializer _jsonSerializer;
  34. private IBrotliCompressor _brotliCompressor;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
  37. /// </summary>
  38. public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor)
  39. {
  40. _fileSystem = fileSystem;
  41. _jsonSerializer = jsonSerializer;
  42. _brotliCompressor = brotliCompressor;
  43. _logger = loggerfactory.CreateLogger("HttpResultFactory");
  44. }
  45. /// <summary>
  46. /// Gets the result.
  47. /// </summary>
  48. /// <param name="content">The content.</param>
  49. /// <param name="contentType">Type of the content.</param>
  50. /// <param name="responseHeaders">The response headers.</param>
  51. /// <returns>System.Object.</returns>
  52. public object GetResult(IRequest requestContext, byte[] content, string contentType, IDictionary<string, string> responseHeaders = null)
  53. {
  54. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  55. }
  56. public object GetResult(string content, string contentType, IDictionary<string, string> responseHeaders = null)
  57. {
  58. return GetHttpResult(null, content, contentType, true, responseHeaders);
  59. }
  60. public object GetResult(IRequest requestContext, Stream content, string contentType, IDictionary<string, string> responseHeaders = null)
  61. {
  62. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  63. }
  64. public object GetResult(IRequest requestContext, string content, string contentType, IDictionary<string, string> responseHeaders = null)
  65. {
  66. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  67. }
  68. public object GetRedirectResult(string url)
  69. {
  70. var responseHeaders = new Dictionary<string, string>();
  71. responseHeaders["Location"] = url;
  72. var result = new HttpResult(Array.Empty<byte>(), "text/plain", HttpStatusCode.Redirect);
  73. AddResponseHeaders(result, responseHeaders);
  74. return result;
  75. }
  76. /// <summary>
  77. /// Gets the HTTP result.
  78. /// </summary>
  79. private IHasHeaders GetHttpResult(IRequest requestContext, Stream content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  80. {
  81. var result = new StreamWriter(content, contentType);
  82. if (responseHeaders == null)
  83. {
  84. responseHeaders = new Dictionary<string, string>();
  85. }
  86. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string expires))
  87. {
  88. responseHeaders["Expires"] = "-1";
  89. }
  90. AddResponseHeaders(result, responseHeaders);
  91. return result;
  92. }
  93. /// <summary>
  94. /// Gets the HTTP result.
  95. /// </summary>
  96. private IHasHeaders GetHttpResult(IRequest requestContext, byte[] content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  97. {
  98. string compressionType = null;
  99. bool isHeadRequest = false;
  100. if (requestContext != null)
  101. {
  102. compressionType = GetCompressionType(requestContext, content, contentType);
  103. isHeadRequest = string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase);
  104. }
  105. IHasHeaders result;
  106. if (string.IsNullOrEmpty(compressionType))
  107. {
  108. var contentLength = content.Length;
  109. if (isHeadRequest)
  110. {
  111. content = Array.Empty<byte>();
  112. }
  113. result = new StreamWriter(content, contentType);
  114. }
  115. else
  116. {
  117. result = GetCompressedResult(content, compressionType, responseHeaders, isHeadRequest, contentType);
  118. }
  119. if (responseHeaders == null)
  120. {
  121. responseHeaders = new Dictionary<string, string>();
  122. }
  123. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string _))
  124. {
  125. responseHeaders["Expires"] = "-1";
  126. }
  127. AddResponseHeaders(result, responseHeaders);
  128. return result;
  129. }
  130. /// <summary>
  131. /// Gets the HTTP result.
  132. /// </summary>
  133. private IHasHeaders GetHttpResult(IRequest requestContext, string content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  134. {
  135. IHasHeaders result;
  136. var bytes = Encoding.UTF8.GetBytes(content);
  137. var compressionType = requestContext == null ? null : GetCompressionType(requestContext, bytes, contentType);
  138. var isHeadRequest = requestContext == null ? false : string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase);
  139. if (string.IsNullOrEmpty(compressionType))
  140. {
  141. var contentLength = bytes.Length;
  142. if (isHeadRequest)
  143. {
  144. bytes = Array.Empty<byte>();
  145. }
  146. result = new StreamWriter(bytes, contentType);
  147. }
  148. else
  149. {
  150. result = GetCompressedResult(bytes, compressionType, responseHeaders, isHeadRequest, contentType);
  151. }
  152. if (responseHeaders == null)
  153. {
  154. responseHeaders = new Dictionary<string, string>();
  155. }
  156. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string _))
  157. {
  158. responseHeaders["Expires"] = "-1";
  159. }
  160. AddResponseHeaders(result, responseHeaders);
  161. return result;
  162. }
  163. /// <summary>
  164. /// Gets the optimized result.
  165. /// </summary>
  166. /// <typeparam name="T"></typeparam>
  167. public object GetResult<T>(IRequest requestContext, T result, IDictionary<string, string> responseHeaders = null)
  168. where T : class
  169. {
  170. if (result == null)
  171. {
  172. throw new ArgumentNullException(nameof(result));
  173. }
  174. if (responseHeaders == null)
  175. {
  176. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  177. }
  178. responseHeaders["Expires"] = "-1";
  179. return ToOptimizedResultInternal(requestContext, result, responseHeaders);
  180. }
  181. private string GetCompressionType(IRequest request, byte[] content, string responseContentType)
  182. {
  183. if (responseContentType == null)
  184. {
  185. return null;
  186. }
  187. // Per apple docs, hls manifests must be compressed
  188. if (!responseContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) &&
  189. responseContentType.IndexOf("json", StringComparison.OrdinalIgnoreCase) == -1 &&
  190. responseContentType.IndexOf("javascript", StringComparison.OrdinalIgnoreCase) == -1 &&
  191. responseContentType.IndexOf("xml", StringComparison.OrdinalIgnoreCase) == -1 &&
  192. responseContentType.IndexOf("application/x-mpegURL", StringComparison.OrdinalIgnoreCase) == -1)
  193. {
  194. return null;
  195. }
  196. if (content.Length < 1024)
  197. {
  198. return null;
  199. }
  200. return GetCompressionType(request);
  201. }
  202. private static string GetCompressionType(IRequest request)
  203. {
  204. var acceptEncoding = request.Headers["Accept-Encoding"];
  205. if (acceptEncoding != null)
  206. {
  207. //if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
  208. // return "br";
  209. if (acceptEncoding.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
  210. return "deflate";
  211. if (acceptEncoding.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
  212. return "gzip";
  213. }
  214. return null;
  215. }
  216. /// <summary>
  217. /// Returns the optimized result for the IRequestContext.
  218. /// Does not use or store results in any cache.
  219. /// </summary>
  220. /// <param name="request"></param>
  221. /// <param name="dto"></param>
  222. /// <returns></returns>
  223. public object ToOptimizedResult<T>(IRequest request, T dto)
  224. {
  225. return ToOptimizedResultInternal(request, dto);
  226. }
  227. private object ToOptimizedResultInternal<T>(IRequest request, T dto, IDictionary<string, string> responseHeaders = null)
  228. {
  229. // TODO: @bond use Span and .Equals
  230. var contentType = request.ResponseContentType?.Split(';')[0].Trim().ToLowerInvariant();
  231. switch (contentType)
  232. {
  233. case "application/xml":
  234. case "text/xml":
  235. case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
  236. return GetHttpResult(request, SerializeToXmlString(dto), contentType, false, responseHeaders);
  237. case "application/json":
  238. case "text/json":
  239. return GetHttpResult(request, _jsonSerializer.SerializeToString(dto), contentType, false, responseHeaders);
  240. default:
  241. break;
  242. }
  243. var isHeadRequest = string.Equals(request.Verb, "head", StringComparison.OrdinalIgnoreCase);
  244. var ms = new MemoryStream();
  245. var writerFn = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
  246. writerFn(dto, ms);
  247. ms.Position = 0;
  248. if (isHeadRequest)
  249. {
  250. using (ms)
  251. {
  252. return GetHttpResult(request, Array.Empty<byte>(), contentType, true, responseHeaders);
  253. }
  254. }
  255. return GetHttpResult(request, ms, contentType, true, responseHeaders);
  256. }
  257. private IHasHeaders GetCompressedResult(byte[] content,
  258. string requestedCompressionType,
  259. IDictionary<string, string> responseHeaders,
  260. bool isHeadRequest,
  261. string contentType)
  262. {
  263. if (responseHeaders == null)
  264. {
  265. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  266. }
  267. content = Compress(content, requestedCompressionType);
  268. responseHeaders["Content-Encoding"] = requestedCompressionType;
  269. responseHeaders["Vary"] = "Accept-Encoding";
  270. var contentLength = content.Length;
  271. if (isHeadRequest)
  272. {
  273. var result = new StreamWriter(Array.Empty<byte>(), contentType);
  274. AddResponseHeaders(result, responseHeaders);
  275. return result;
  276. }
  277. else
  278. {
  279. var result = new StreamWriter(content, contentType);
  280. AddResponseHeaders(result, responseHeaders);
  281. return result;
  282. }
  283. }
  284. private byte[] Compress(byte[] bytes, string compressionType)
  285. {
  286. if (string.Equals(compressionType, "br", StringComparison.OrdinalIgnoreCase))
  287. {
  288. return CompressBrotli(bytes);
  289. }
  290. if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
  291. {
  292. return Deflate(bytes);
  293. }
  294. if (string.Equals(compressionType, "gzip", StringComparison.OrdinalIgnoreCase))
  295. {
  296. return GZip(bytes);
  297. }
  298. throw new NotSupportedException(compressionType);
  299. }
  300. private byte[] CompressBrotli(byte[] bytes)
  301. {
  302. return _brotliCompressor.Compress(bytes);
  303. }
  304. private static byte[] Deflate(byte[] bytes)
  305. {
  306. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  307. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  308. using (var ms = new MemoryStream())
  309. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  310. {
  311. zipStream.Write(bytes, 0, bytes.Length);
  312. zipStream.Dispose();
  313. return ms.ToArray();
  314. }
  315. }
  316. private static byte[] GZip(byte[] buffer)
  317. {
  318. using (var ms = new MemoryStream())
  319. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  320. {
  321. zipStream.Write(buffer, 0, buffer.Length);
  322. zipStream.Dispose();
  323. return ms.ToArray();
  324. }
  325. }
  326. private static string SerializeToXmlString(object from)
  327. {
  328. using (var ms = new MemoryStream())
  329. {
  330. var xwSettings = new XmlWriterSettings();
  331. xwSettings.Encoding = new UTF8Encoding(false);
  332. xwSettings.OmitXmlDeclaration = false;
  333. using (var xw = XmlWriter.Create(ms, xwSettings))
  334. {
  335. var serializer = new DataContractSerializer(from.GetType());
  336. serializer.WriteObject(xw, from);
  337. xw.Flush();
  338. ms.Seek(0, SeekOrigin.Begin);
  339. using (var reader = new StreamReader(ms))
  340. {
  341. return reader.ReadToEnd();
  342. }
  343. }
  344. }
  345. }
  346. /// <summary>
  347. /// Pres the process optimized result.
  348. /// </summary>
  349. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options)
  350. {
  351. bool noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
  352. AddCachingHeaders(responseHeaders, options.CacheDuration, noCache, options.DateLastModified);
  353. if (!noCache)
  354. {
  355. DateTime.TryParse(requestContext.Headers.Get("If-Modified-Since"), out var ifModifiedSinceHeader);
  356. if (IsNotModified(ifModifiedSinceHeader, options.CacheDuration, options.DateLastModified))
  357. {
  358. AddAgeHeader(responseHeaders, options.DateLastModified);
  359. var result = new HttpResult(Array.Empty<byte>(), options.ContentType ?? "text/html", HttpStatusCode.NotModified);
  360. AddResponseHeaders(result, responseHeaders);
  361. return result;
  362. }
  363. }
  364. return null;
  365. }
  366. public Task<object> GetStaticFileResult(IRequest requestContext,
  367. string path,
  368. FileShareMode fileShare = FileShareMode.Read)
  369. {
  370. if (string.IsNullOrEmpty(path))
  371. {
  372. throw new ArgumentNullException(nameof(path));
  373. }
  374. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  375. {
  376. Path = path,
  377. FileShare = fileShare
  378. });
  379. }
  380. public Task<object> GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options)
  381. {
  382. var path = options.Path;
  383. var fileShare = options.FileShare;
  384. if (string.IsNullOrEmpty(path))
  385. {
  386. throw new ArgumentNullException(nameof(path));
  387. }
  388. if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
  389. {
  390. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  391. }
  392. if (string.IsNullOrEmpty(options.ContentType))
  393. {
  394. options.ContentType = MimeTypes.GetMimeType(path);
  395. }
  396. if (!options.DateLastModified.HasValue)
  397. {
  398. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  399. }
  400. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  401. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  402. return GetStaticResult(requestContext, options);
  403. }
  404. /// <summary>
  405. /// Gets the file stream.
  406. /// </summary>
  407. /// <param name="path">The path.</param>
  408. /// <param name="fileShare">The file share.</param>
  409. /// <returns>Stream.</returns>
  410. private Stream GetFileStream(string path, FileShareMode fileShare)
  411. {
  412. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  413. }
  414. public Task<object> GetStaticResult(IRequest requestContext,
  415. Guid cacheKey,
  416. DateTime? lastDateModified,
  417. TimeSpan? cacheDuration,
  418. string contentType,
  419. Func<Task<Stream>> factoryFn,
  420. IDictionary<string, string> responseHeaders = null,
  421. bool isHeadRequest = false)
  422. {
  423. return GetStaticResult(requestContext, new StaticResultOptions
  424. {
  425. CacheDuration = cacheDuration,
  426. ContentFactory = factoryFn,
  427. ContentType = contentType,
  428. DateLastModified = lastDateModified,
  429. IsHeadRequest = isHeadRequest,
  430. ResponseHeaders = responseHeaders
  431. });
  432. }
  433. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  434. {
  435. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  436. var contentType = options.ContentType;
  437. if (!string.IsNullOrEmpty(requestContext.Headers.Get("If-Modified-Since")))
  438. {
  439. // See if the result is already cached in the browser
  440. var result = GetCachedResult(requestContext, options.ResponseHeaders, options);
  441. if (result != null)
  442. {
  443. return result;
  444. }
  445. }
  446. // TODO: We don't really need the option value
  447. var isHeadRequest = options.IsHeadRequest || string.Equals(requestContext.Verb, "HEAD", StringComparison.OrdinalIgnoreCase);
  448. var factoryFn = options.ContentFactory;
  449. var responseHeaders = options.ResponseHeaders;
  450. AddCachingHeaders(responseHeaders, options.CacheDuration, false, options.DateLastModified);
  451. AddAgeHeader(responseHeaders, options.DateLastModified);
  452. var rangeHeader = requestContext.Headers.Get("Range");
  453. if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
  454. {
  455. var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
  456. {
  457. OnComplete = options.OnComplete,
  458. OnError = options.OnError,
  459. FileShare = options.FileShare
  460. };
  461. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  462. return hasHeaders;
  463. }
  464. var stream = await factoryFn().ConfigureAwait(false);
  465. var totalContentLength = options.ContentLength;
  466. if (!totalContentLength.HasValue)
  467. {
  468. try
  469. {
  470. totalContentLength = stream.Length;
  471. }
  472. catch (NotSupportedException)
  473. {
  474. }
  475. }
  476. if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue)
  477. {
  478. var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest, _logger)
  479. {
  480. OnComplete = options.OnComplete
  481. };
  482. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  483. return hasHeaders;
  484. }
  485. else
  486. {
  487. if (isHeadRequest)
  488. {
  489. using (stream)
  490. {
  491. return GetHttpResult(requestContext, Array.Empty<byte>(), contentType, true, responseHeaders);
  492. }
  493. }
  494. var hasHeaders = new StreamWriter(stream, contentType)
  495. {
  496. OnComplete = options.OnComplete,
  497. OnError = options.OnError
  498. };
  499. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  500. return hasHeaders;
  501. }
  502. }
  503. /// <summary>
  504. /// The us culture
  505. /// </summary>
  506. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  507. /// <summary>
  508. /// Adds the caching responseHeaders.
  509. /// </summary>
  510. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, TimeSpan? cacheDuration,
  511. bool noCache, DateTime? lastModifiedDate)
  512. {
  513. if (noCache)
  514. {
  515. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  516. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  517. return;
  518. }
  519. if (cacheDuration.HasValue)
  520. {
  521. responseHeaders["Cache-Control"] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
  522. }
  523. else
  524. {
  525. responseHeaders["Cache-Control"] = "public";
  526. }
  527. if (lastModifiedDate.HasValue)
  528. {
  529. responseHeaders["Last-Modified"] = lastModifiedDate.ToString();
  530. }
  531. }
  532. /// <summary>
  533. /// Adds the age header.
  534. /// </summary>
  535. /// <param name="responseHeaders">The responseHeaders.</param>
  536. /// <param name="lastDateModified">The last date modified.</param>
  537. private static void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  538. {
  539. if (lastDateModified.HasValue)
  540. {
  541. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  542. }
  543. }
  544. /// <summary>
  545. /// Determines whether [is not modified] [the specified if modified since].
  546. /// </summary>
  547. /// <param name="ifModifiedSince">If modified since.</param>
  548. /// <param name="cacheDuration">Duration of the cache.</param>
  549. /// <param name="dateModified">The date modified.</param>
  550. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  551. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  552. {
  553. if (dateModified.HasValue)
  554. {
  555. var lastModified = NormalizeDateForComparison(dateModified.Value);
  556. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  557. return lastModified <= ifModifiedSince;
  558. }
  559. if (cacheDuration.HasValue)
  560. {
  561. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  562. if (DateTime.UtcNow < cacheExpirationDate)
  563. {
  564. return true;
  565. }
  566. }
  567. return false;
  568. }
  569. /// <summary>
  570. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  571. /// </summary>
  572. /// <param name="date">The date.</param>
  573. /// <returns>DateTime.</returns>
  574. private static DateTime NormalizeDateForComparison(DateTime date)
  575. {
  576. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  577. }
  578. /// <summary>
  579. /// Adds the response headers.
  580. /// </summary>
  581. /// <param name="hasHeaders">The has options.</param>
  582. /// <param name="responseHeaders">The response headers.</param>
  583. private static void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  584. {
  585. foreach (var item in responseHeaders)
  586. {
  587. hasHeaders.Headers[item.Key] = item.Value;
  588. }
  589. }
  590. }
  591. public interface IBrotliCompressor
  592. {
  593. byte[] Compress(byte[] content);
  594. }
  595. }