HttpResultFactory.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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, _logger);
  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, contentLength, _logger);
  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 expires))
  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, contentLength, _logger);
  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 expires))
  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. var contentType = request.ResponseContentType;
  230. switch (GetRealContentType(contentType))
  231. {
  232. case "application/xml":
  233. case "text/xml":
  234. case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
  235. return GetHttpResult(request, SerializeToXmlString(dto), contentType, false, responseHeaders);
  236. case "application/json":
  237. case "text/json":
  238. return GetHttpResult(request, _jsonSerializer.SerializeToString(dto), contentType, false, responseHeaders);
  239. default:
  240. break;
  241. }
  242. var isHeadRequest = string.Equals(request.Verb, "head", StringComparison.OrdinalIgnoreCase);
  243. var ms = new MemoryStream();
  244. var writerFn = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
  245. writerFn(dto, ms);
  246. ms.Position = 0;
  247. if (isHeadRequest)
  248. {
  249. using (ms)
  250. {
  251. return GetHttpResult(request, Array.Empty<byte>(), contentType, true, responseHeaders);
  252. }
  253. }
  254. return GetHttpResult(request, ms, contentType, true, responseHeaders);
  255. }
  256. private IHasHeaders GetCompressedResult(byte[] content,
  257. string requestedCompressionType,
  258. IDictionary<string, string> responseHeaders,
  259. bool isHeadRequest,
  260. string contentType)
  261. {
  262. if (responseHeaders == null)
  263. {
  264. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  265. }
  266. content = Compress(content, requestedCompressionType);
  267. responseHeaders["Content-Encoding"] = requestedCompressionType;
  268. responseHeaders["Vary"] = "Accept-Encoding";
  269. var contentLength = content.Length;
  270. if (isHeadRequest)
  271. {
  272. var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength, _logger);
  273. AddResponseHeaders(result, responseHeaders);
  274. return result;
  275. }
  276. else
  277. {
  278. var result = new StreamWriter(content, contentType, contentLength, _logger);
  279. AddResponseHeaders(result, responseHeaders);
  280. return result;
  281. }
  282. }
  283. private byte[] Compress(byte[] bytes, string compressionType)
  284. {
  285. if (string.Equals(compressionType, "br", StringComparison.OrdinalIgnoreCase))
  286. return CompressBrotli(bytes);
  287. if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
  288. return Deflate(bytes);
  289. if (string.Equals(compressionType, "gzip", StringComparison.OrdinalIgnoreCase))
  290. return GZip(bytes);
  291. throw new NotSupportedException(compressionType);
  292. }
  293. private byte[] CompressBrotli(byte[] bytes)
  294. {
  295. return _brotliCompressor.Compress(bytes);
  296. }
  297. private static byte[] Deflate(byte[] bytes)
  298. {
  299. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  300. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  301. using (var ms = new MemoryStream())
  302. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  303. {
  304. zipStream.Write(bytes, 0, bytes.Length);
  305. zipStream.Dispose();
  306. return ms.ToArray();
  307. }
  308. }
  309. private static byte[] GZip(byte[] buffer)
  310. {
  311. using (var ms = new MemoryStream())
  312. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  313. {
  314. zipStream.Write(buffer, 0, buffer.Length);
  315. zipStream.Dispose();
  316. return ms.ToArray();
  317. }
  318. }
  319. public static string GetRealContentType(string contentType)
  320. {
  321. return contentType == null
  322. ? null
  323. : contentType.Split(';')[0].ToLowerInvariant().Trim();
  324. }
  325. private static string SerializeToXmlString(object from)
  326. {
  327. using (var ms = new MemoryStream())
  328. {
  329. var xwSettings = new XmlWriterSettings();
  330. xwSettings.Encoding = new UTF8Encoding(false);
  331. xwSettings.OmitXmlDeclaration = false;
  332. using (var xw = XmlWriter.Create(ms, xwSettings))
  333. {
  334. var serializer = new DataContractSerializer(from.GetType());
  335. serializer.WriteObject(xw, from);
  336. xw.Flush();
  337. ms.Seek(0, SeekOrigin.Begin);
  338. using (var reader = new StreamReader(ms))
  339. {
  340. return reader.ReadToEnd();
  341. }
  342. }
  343. }
  344. }
  345. /// <summary>
  346. /// Pres the process optimized result.
  347. /// </summary>
  348. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options)
  349. {
  350. bool noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
  351. AddCachingHeaders(responseHeaders, options.CacheDuration, noCache, options.DateLastModified);
  352. if (!noCache)
  353. {
  354. DateTime.TryParse(requestContext.Headers.Get("If-Modified-Since"), out var ifModifiedSinceHeader);
  355. if (IsNotModified(ifModifiedSinceHeader, options.CacheDuration, options.DateLastModified))
  356. {
  357. AddAgeHeader(responseHeaders, options.DateLastModified);
  358. var result = new HttpResult(Array.Empty<byte>(), options.ContentType ?? "text/html", HttpStatusCode.NotModified);
  359. AddResponseHeaders(result, responseHeaders);
  360. return result;
  361. }
  362. }
  363. return null;
  364. }
  365. public Task<object> GetStaticFileResult(IRequest requestContext,
  366. string path,
  367. FileShareMode fileShare = FileShareMode.Read)
  368. {
  369. if (string.IsNullOrEmpty(path))
  370. {
  371. throw new ArgumentNullException(nameof(path));
  372. }
  373. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  374. {
  375. Path = path,
  376. FileShare = fileShare
  377. });
  378. }
  379. public Task<object> GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options)
  380. {
  381. var path = options.Path;
  382. var fileShare = options.FileShare;
  383. if (string.IsNullOrEmpty(path))
  384. {
  385. throw new ArgumentNullException(nameof(path));
  386. }
  387. if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
  388. {
  389. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  390. }
  391. if (string.IsNullOrEmpty(options.ContentType))
  392. {
  393. options.ContentType = MimeTypes.GetMimeType(path);
  394. }
  395. if (!options.DateLastModified.HasValue)
  396. {
  397. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  398. }
  399. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  400. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  401. return GetStaticResult(requestContext, options);
  402. }
  403. /// <summary>
  404. /// Gets the file stream.
  405. /// </summary>
  406. /// <param name="path">The path.</param>
  407. /// <param name="fileShare">The file share.</param>
  408. /// <returns>Stream.</returns>
  409. private Stream GetFileStream(string path, FileShareMode fileShare)
  410. {
  411. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  412. }
  413. public Task<object> GetStaticResult(IRequest requestContext,
  414. Guid cacheKey,
  415. DateTime? lastDateModified,
  416. TimeSpan? cacheDuration,
  417. string contentType,
  418. Func<Task<Stream>> factoryFn,
  419. IDictionary<string, string> responseHeaders = null,
  420. bool isHeadRequest = false)
  421. {
  422. return GetStaticResult(requestContext, new StaticResultOptions
  423. {
  424. CacheDuration = cacheDuration,
  425. ContentFactory = factoryFn,
  426. ContentType = contentType,
  427. DateLastModified = lastDateModified,
  428. IsHeadRequest = isHeadRequest,
  429. ResponseHeaders = responseHeaders
  430. });
  431. }
  432. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  433. {
  434. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  435. var contentType = options.ContentType;
  436. if (!string.IsNullOrEmpty(requestContext.Headers.Get("If-Modified-Since")))
  437. {
  438. // See if the result is already cached in the browser
  439. var result = GetCachedResult(requestContext, options.ResponseHeaders, options);
  440. if (result != null)
  441. {
  442. return result;
  443. }
  444. }
  445. // TODO: We don't really need the option value
  446. var isHeadRequest = options.IsHeadRequest || string.Equals(requestContext.Verb, "HEAD", StringComparison.OrdinalIgnoreCase);
  447. var factoryFn = options.ContentFactory;
  448. var responseHeaders = options.ResponseHeaders;
  449. AddCachingHeaders(responseHeaders, options.CacheDuration, false, options.DateLastModified);
  450. AddAgeHeader(responseHeaders, options.DateLastModified);
  451. var rangeHeader = requestContext.Headers.Get("Range");
  452. if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
  453. {
  454. var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
  455. {
  456. OnComplete = options.OnComplete,
  457. OnError = options.OnError,
  458. FileShare = options.FileShare
  459. };
  460. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  461. return hasHeaders;
  462. }
  463. var stream = await factoryFn().ConfigureAwait(false);
  464. var totalContentLength = options.ContentLength;
  465. if (!totalContentLength.HasValue)
  466. {
  467. try
  468. {
  469. totalContentLength = stream.Length;
  470. }
  471. catch (NotSupportedException)
  472. {
  473. }
  474. }
  475. if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue)
  476. {
  477. var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest, _logger)
  478. {
  479. OnComplete = options.OnComplete
  480. };
  481. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  482. return hasHeaders;
  483. }
  484. else
  485. {
  486. if (totalContentLength.HasValue)
  487. {
  488. responseHeaders["Content-Length"] = totalContentLength.Value.ToString(UsCulture);
  489. }
  490. if (isHeadRequest)
  491. {
  492. using (stream)
  493. {
  494. return GetHttpResult(requestContext, Array.Empty<byte>(), contentType, true, responseHeaders);
  495. }
  496. }
  497. var hasHeaders = new StreamWriter(stream, contentType, _logger)
  498. {
  499. OnComplete = options.OnComplete,
  500. OnError = options.OnError
  501. };
  502. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  503. return hasHeaders;
  504. }
  505. }
  506. /// <summary>
  507. /// The us culture
  508. /// </summary>
  509. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  510. /// <summary>
  511. /// Adds the caching responseHeaders.
  512. /// </summary>
  513. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, TimeSpan? cacheDuration,
  514. bool noCache, DateTime? lastModifiedDate)
  515. {
  516. if (noCache)
  517. {
  518. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  519. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  520. return;
  521. }
  522. if (cacheDuration.HasValue)
  523. {
  524. responseHeaders["Cache-Control"] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
  525. }
  526. else
  527. {
  528. responseHeaders["Cache-Control"] = "public";
  529. }
  530. if (lastModifiedDate.HasValue)
  531. {
  532. responseHeaders["Last-Modified"] = lastModifiedDate.ToString();
  533. }
  534. }
  535. /// <summary>
  536. /// Adds the age header.
  537. /// </summary>
  538. /// <param name="responseHeaders">The responseHeaders.</param>
  539. /// <param name="lastDateModified">The last date modified.</param>
  540. private static void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  541. {
  542. if (lastDateModified.HasValue)
  543. {
  544. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  545. }
  546. }
  547. /// <summary>
  548. /// Determines whether [is not modified] [the specified if modified since].
  549. /// </summary>
  550. /// <param name="ifModifiedSince">If modified since.</param>
  551. /// <param name="cacheDuration">Duration of the cache.</param>
  552. /// <param name="dateModified">The date modified.</param>
  553. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  554. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  555. {
  556. if (dateModified.HasValue)
  557. {
  558. var lastModified = NormalizeDateForComparison(dateModified.Value);
  559. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  560. return lastModified <= ifModifiedSince;
  561. }
  562. if (cacheDuration.HasValue)
  563. {
  564. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  565. if (DateTime.UtcNow < cacheExpirationDate)
  566. {
  567. return true;
  568. }
  569. }
  570. return false;
  571. }
  572. /// <summary>
  573. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  574. /// </summary>
  575. /// <param name="date">The date.</param>
  576. /// <returns>DateTime.</returns>
  577. private static DateTime NormalizeDateForComparison(DateTime date)
  578. {
  579. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  580. }
  581. /// <summary>
  582. /// Adds the response headers.
  583. /// </summary>
  584. /// <param name="hasHeaders">The has options.</param>
  585. /// <param name="responseHeaders">The response headers.</param>
  586. private static void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  587. {
  588. foreach (var item in responseHeaders)
  589. {
  590. hasHeaders.Headers[item.Key] = item.Value;
  591. }
  592. }
  593. }
  594. public interface IBrotliCompressor
  595. {
  596. byte[] Compress(byte[] content);
  597. }
  598. }