HttpResultFactory.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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 Microsoft.Extensions.Primitives;
  20. using Microsoft.Net.Http.Headers;
  21. using IRequest = MediaBrowser.Model.Services.IRequest;
  22. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  23. namespace Emby.Server.Implementations.HttpServer
  24. {
  25. /// <summary>
  26. /// Class HttpResultFactory
  27. /// </summary>
  28. public class HttpResultFactory : IHttpResultFactory
  29. {
  30. /// <summary>
  31. /// The _logger
  32. /// </summary>
  33. private readonly ILogger _logger;
  34. private readonly IFileSystem _fileSystem;
  35. private readonly IJsonSerializer _jsonSerializer;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
  38. /// </summary>
  39. public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer)
  40. {
  41. _fileSystem = fileSystem;
  42. _jsonSerializer = jsonSerializer;
  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"].ToString();
  205. if (string.IsNullOrEmpty(acceptEncoding))
  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, "deflate", StringComparison.OrdinalIgnoreCase))
  287. {
  288. return Deflate(bytes);
  289. }
  290. if (string.Equals(compressionType, "gzip", StringComparison.OrdinalIgnoreCase))
  291. {
  292. return GZip(bytes);
  293. }
  294. throw new NotSupportedException(compressionType);
  295. }
  296. private static byte[] Deflate(byte[] bytes)
  297. {
  298. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  299. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  300. using (var ms = new MemoryStream())
  301. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  302. {
  303. zipStream.Write(bytes, 0, bytes.Length);
  304. zipStream.Dispose();
  305. return ms.ToArray();
  306. }
  307. }
  308. private static byte[] GZip(byte[] buffer)
  309. {
  310. using (var ms = new MemoryStream())
  311. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  312. {
  313. zipStream.Write(buffer, 0, buffer.Length);
  314. zipStream.Dispose();
  315. return ms.ToArray();
  316. }
  317. }
  318. private static string SerializeToXmlString(object from)
  319. {
  320. using (var ms = new MemoryStream())
  321. {
  322. var xwSettings = new XmlWriterSettings();
  323. xwSettings.Encoding = new UTF8Encoding(false);
  324. xwSettings.OmitXmlDeclaration = false;
  325. using (var xw = XmlWriter.Create(ms, xwSettings))
  326. {
  327. var serializer = new DataContractSerializer(from.GetType());
  328. serializer.WriteObject(xw, from);
  329. xw.Flush();
  330. ms.Seek(0, SeekOrigin.Begin);
  331. using (var reader = new StreamReader(ms))
  332. {
  333. return reader.ReadToEnd();
  334. }
  335. }
  336. }
  337. }
  338. /// <summary>
  339. /// Pres the process optimized result.
  340. /// </summary>
  341. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options)
  342. {
  343. bool noCache = (requestContext.Headers[HeaderNames.CacheControl].ToString()).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
  344. AddCachingHeaders(responseHeaders, options.CacheDuration, noCache, options.DateLastModified);
  345. if (!noCache)
  346. {
  347. DateTime.TryParse(requestContext.Headers[HeaderNames.IfModifiedSince], out var ifModifiedSinceHeader);
  348. if (IsNotModified(ifModifiedSinceHeader, options.CacheDuration, options.DateLastModified))
  349. {
  350. AddAgeHeader(responseHeaders, options.DateLastModified);
  351. var result = new HttpResult(Array.Empty<byte>(), options.ContentType ?? "text/html", HttpStatusCode.NotModified);
  352. AddResponseHeaders(result, responseHeaders);
  353. return result;
  354. }
  355. }
  356. return null;
  357. }
  358. public Task<object> GetStaticFileResult(IRequest requestContext,
  359. string path,
  360. FileShareMode fileShare = FileShareMode.Read)
  361. {
  362. if (string.IsNullOrEmpty(path))
  363. {
  364. throw new ArgumentNullException(nameof(path));
  365. }
  366. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  367. {
  368. Path = path,
  369. FileShare = fileShare
  370. });
  371. }
  372. public Task<object> GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options)
  373. {
  374. var path = options.Path;
  375. var fileShare = options.FileShare;
  376. if (string.IsNullOrEmpty(path))
  377. {
  378. throw new ArgumentNullException(nameof(path));
  379. }
  380. if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
  381. {
  382. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  383. }
  384. if (string.IsNullOrEmpty(options.ContentType))
  385. {
  386. options.ContentType = MimeTypes.GetMimeType(path);
  387. }
  388. if (!options.DateLastModified.HasValue)
  389. {
  390. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  391. }
  392. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  393. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  394. return GetStaticResult(requestContext, options);
  395. }
  396. /// <summary>
  397. /// Gets the file stream.
  398. /// </summary>
  399. /// <param name="path">The path.</param>
  400. /// <param name="fileShare">The file share.</param>
  401. /// <returns>Stream.</returns>
  402. private Stream GetFileStream(string path, FileShareMode fileShare)
  403. {
  404. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  405. }
  406. public Task<object> GetStaticResult(IRequest requestContext,
  407. Guid cacheKey,
  408. DateTime? lastDateModified,
  409. TimeSpan? cacheDuration,
  410. string contentType,
  411. Func<Task<Stream>> factoryFn,
  412. IDictionary<string, string> responseHeaders = null,
  413. bool isHeadRequest = false)
  414. {
  415. return GetStaticResult(requestContext, new StaticResultOptions
  416. {
  417. CacheDuration = cacheDuration,
  418. ContentFactory = factoryFn,
  419. ContentType = contentType,
  420. DateLastModified = lastDateModified,
  421. IsHeadRequest = isHeadRequest,
  422. ResponseHeaders = responseHeaders
  423. });
  424. }
  425. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  426. {
  427. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  428. var contentType = options.ContentType;
  429. if (!StringValues.IsNullOrEmpty(requestContext.Headers[HeaderNames.IfModifiedSince]))
  430. {
  431. // See if the result is already cached in the browser
  432. var result = GetCachedResult(requestContext, options.ResponseHeaders, options);
  433. if (result != null)
  434. {
  435. return result;
  436. }
  437. }
  438. // TODO: We don't really need the option value
  439. var isHeadRequest = options.IsHeadRequest || string.Equals(requestContext.Verb, "HEAD", StringComparison.OrdinalIgnoreCase);
  440. var factoryFn = options.ContentFactory;
  441. var responseHeaders = options.ResponseHeaders;
  442. AddCachingHeaders(responseHeaders, options.CacheDuration, false, options.DateLastModified);
  443. AddAgeHeader(responseHeaders, options.DateLastModified);
  444. var rangeHeader = requestContext.Headers["Range"];
  445. if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
  446. {
  447. var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
  448. {
  449. OnComplete = options.OnComplete,
  450. OnError = options.OnError,
  451. FileShare = options.FileShare
  452. };
  453. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  454. return hasHeaders;
  455. }
  456. var stream = await factoryFn().ConfigureAwait(false);
  457. var totalContentLength = options.ContentLength;
  458. if (!totalContentLength.HasValue)
  459. {
  460. try
  461. {
  462. totalContentLength = stream.Length;
  463. }
  464. catch (NotSupportedException)
  465. {
  466. }
  467. }
  468. if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue)
  469. {
  470. var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest, _logger)
  471. {
  472. OnComplete = options.OnComplete
  473. };
  474. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  475. return hasHeaders;
  476. }
  477. else
  478. {
  479. if (isHeadRequest)
  480. {
  481. using (stream)
  482. {
  483. return GetHttpResult(requestContext, Array.Empty<byte>(), contentType, true, responseHeaders);
  484. }
  485. }
  486. var hasHeaders = new StreamWriter(stream, contentType)
  487. {
  488. OnComplete = options.OnComplete,
  489. OnError = options.OnError
  490. };
  491. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  492. return hasHeaders;
  493. }
  494. }
  495. /// <summary>
  496. /// Adds the caching responseHeaders.
  497. /// </summary>
  498. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, TimeSpan? cacheDuration,
  499. bool noCache, DateTime? lastModifiedDate)
  500. {
  501. if (noCache)
  502. {
  503. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  504. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  505. return;
  506. }
  507. if (cacheDuration.HasValue)
  508. {
  509. responseHeaders["Cache-Control"] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
  510. }
  511. else
  512. {
  513. responseHeaders["Cache-Control"] = "public";
  514. }
  515. if (lastModifiedDate.HasValue)
  516. {
  517. responseHeaders["Last-Modified"] = lastModifiedDate.ToString();
  518. }
  519. }
  520. /// <summary>
  521. /// Adds the age header.
  522. /// </summary>
  523. /// <param name="responseHeaders">The responseHeaders.</param>
  524. /// <param name="lastDateModified">The last date modified.</param>
  525. private static void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  526. {
  527. if (lastDateModified.HasValue)
  528. {
  529. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  530. }
  531. }
  532. /// <summary>
  533. /// Determines whether [is not modified] [the specified if modified since].
  534. /// </summary>
  535. /// <param name="ifModifiedSince">If modified since.</param>
  536. /// <param name="cacheDuration">Duration of the cache.</param>
  537. /// <param name="dateModified">The date modified.</param>
  538. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  539. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  540. {
  541. if (dateModified.HasValue)
  542. {
  543. var lastModified = NormalizeDateForComparison(dateModified.Value);
  544. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  545. return lastModified <= ifModifiedSince;
  546. }
  547. if (cacheDuration.HasValue)
  548. {
  549. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  550. if (DateTime.UtcNow < cacheExpirationDate)
  551. {
  552. return true;
  553. }
  554. }
  555. return false;
  556. }
  557. /// <summary>
  558. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  559. /// </summary>
  560. /// <param name="date">The date.</param>
  561. /// <returns>DateTime.</returns>
  562. private static DateTime NormalizeDateForComparison(DateTime date)
  563. {
  564. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  565. }
  566. /// <summary>
  567. /// Adds the response headers.
  568. /// </summary>
  569. /// <param name="hasHeaders">The has options.</param>
  570. /// <param name="responseHeaders">The response headers.</param>
  571. private static void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  572. {
  573. foreach (var item in responseHeaders)
  574. {
  575. hasHeaders.Headers[item.Key] = item.Value;
  576. }
  577. }
  578. }
  579. public interface IBrotliCompressor
  580. {
  581. byte[] Compress(byte[] content);
  582. }
  583. }