HttpResultFactory.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Net;
  3. using Microsoft.Extensions.Logging;
  4. using MediaBrowser.Model.Serialization;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.IO.Compression;
  10. using System.Net;
  11. using System.Runtime.Serialization;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using System.Xml;
  15. using Emby.Server.Implementations.Services;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.Services;
  18. using IRequest = MediaBrowser.Model.Services.IRequest;
  19. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  20. namespace Emby.Server.Implementations.HttpServer
  21. {
  22. /// <summary>
  23. /// Class HttpResultFactory
  24. /// </summary>
  25. public class HttpResultFactory : IHttpResultFactory
  26. {
  27. /// <summary>
  28. /// The _logger
  29. /// </summary>
  30. private readonly ILogger _logger;
  31. private readonly IFileSystem _fileSystem;
  32. private readonly IJsonSerializer _jsonSerializer;
  33. private IBrotliCompressor _brotliCompressor;
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
  36. /// </summary>
  37. public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor)
  38. {
  39. _fileSystem = fileSystem;
  40. _jsonSerializer = jsonSerializer;
  41. _brotliCompressor = brotliCompressor;
  42. _logger = loggerfactory.CreateLogger("HttpResultFactory");
  43. }
  44. /// <summary>
  45. /// Gets the result.
  46. /// </summary>
  47. /// <param name="content">The content.</param>
  48. /// <param name="contentType">Type of the content.</param>
  49. /// <param name="responseHeaders">The response headers.</param>
  50. /// <returns>System.Object.</returns>
  51. public object GetResult(IRequest requestContext, byte[] content, string contentType, IDictionary<string, string> responseHeaders = null)
  52. {
  53. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  54. }
  55. public object GetResult(string content, string contentType, IDictionary<string, string> responseHeaders = null)
  56. {
  57. return GetHttpResult(null, content, contentType, true, responseHeaders);
  58. }
  59. public object GetResult(IRequest requestContext, Stream content, string contentType, IDictionary<string, string> responseHeaders = null)
  60. {
  61. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  62. }
  63. public object GetResult(IRequest requestContext, string content, string contentType, IDictionary<string, string> responseHeaders = null)
  64. {
  65. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  66. }
  67. public object GetRedirectResult(string url)
  68. {
  69. var responseHeaders = new Dictionary<string, string>();
  70. responseHeaders["Location"] = url;
  71. var result = new HttpResult(Array.Empty<byte>(), "text/plain", HttpStatusCode.Redirect);
  72. AddResponseHeaders(result, responseHeaders);
  73. return result;
  74. }
  75. /// <summary>
  76. /// Gets the HTTP result.
  77. /// </summary>
  78. private IHasHeaders GetHttpResult(IRequest requestContext, Stream content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  79. {
  80. var result = new StreamWriter(content, contentType, _logger);
  81. if (responseHeaders == null)
  82. {
  83. responseHeaders = new Dictionary<string, string>();
  84. }
  85. string expires;
  86. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out 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. compressionType = GetCompressionType(requestContext, content, contentType);
  102. isHeadRequest = string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase);
  103. }
  104. IHasHeaders result;
  105. if (string.IsNullOrEmpty(compressionType))
  106. {
  107. var contentLength = content.Length;
  108. if (isHeadRequest)
  109. {
  110. content = Array.Empty<byte>();
  111. }
  112. result = new StreamWriter(content, contentType, contentLength, _logger);
  113. }
  114. else
  115. {
  116. result = GetCompressedResult(content, compressionType, responseHeaders, isHeadRequest, contentType);
  117. }
  118. if (responseHeaders == null)
  119. {
  120. responseHeaders = new Dictionary<string, string>();
  121. }
  122. string expires;
  123. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out 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. string expires;
  157. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out expires))
  158. {
  159. responseHeaders["Expires"] = "-1";
  160. }
  161. AddResponseHeaders(result, responseHeaders);
  162. return result;
  163. }
  164. /// <summary>
  165. /// Gets the optimized result.
  166. /// </summary>
  167. /// <typeparam name="T"></typeparam>
  168. public object GetResult<T>(IRequest requestContext, T result, IDictionary<string, string> responseHeaders = null)
  169. where T : class
  170. {
  171. if (result == null)
  172. {
  173. throw new ArgumentNullException("result");
  174. }
  175. if (responseHeaders == null)
  176. {
  177. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  178. }
  179. responseHeaders["Expires"] = "-1";
  180. return ToOptimizedResultInternal(requestContext, result, responseHeaders);
  181. }
  182. private string GetCompressionType(IRequest request, byte[] content, string responseContentType)
  183. {
  184. if (responseContentType == null)
  185. {
  186. return null;
  187. }
  188. // Per apple docs, hls manifests must be compressed
  189. if (!responseContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) &&
  190. responseContentType.IndexOf("json", StringComparison.OrdinalIgnoreCase) == -1 &&
  191. responseContentType.IndexOf("javascript", StringComparison.OrdinalIgnoreCase) == -1 &&
  192. responseContentType.IndexOf("xml", StringComparison.OrdinalIgnoreCase) == -1 &&
  193. responseContentType.IndexOf("application/x-mpegURL", StringComparison.OrdinalIgnoreCase) == -1)
  194. {
  195. return null;
  196. }
  197. if (content.Length < 1024)
  198. {
  199. return null;
  200. }
  201. return GetCompressionType(request);
  202. }
  203. private string GetCompressionType(IRequest request)
  204. {
  205. var acceptEncoding = request.Headers["Accept-Encoding"];
  206. if (acceptEncoding != null)
  207. {
  208. //if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
  209. // return "br";
  210. if (acceptEncoding.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
  211. return "deflate";
  212. if (acceptEncoding.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
  213. return "gzip";
  214. }
  215. return null;
  216. }
  217. /// <summary>
  218. /// Returns the optimized result for the IRequestContext.
  219. /// Does not use or store results in any cache.
  220. /// </summary>
  221. /// <param name="request"></param>
  222. /// <param name="dto"></param>
  223. /// <returns></returns>
  224. public object ToOptimizedResult<T>(IRequest request, T dto)
  225. {
  226. return ToOptimizedResultInternal(request, dto);
  227. }
  228. private object ToOptimizedResultInternal<T>(IRequest request, T dto, IDictionary<string, string> responseHeaders = null)
  229. {
  230. var contentType = request.ResponseContentType;
  231. switch (GetRealContentType(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, contentLength, _logger);
  274. AddResponseHeaders(result, responseHeaders);
  275. return result;
  276. }
  277. else
  278. {
  279. var result = new StreamWriter(content, contentType, contentLength, _logger);
  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. return CompressBrotli(bytes);
  288. if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
  289. return Deflate(bytes);
  290. if (string.Equals(compressionType, "gzip", StringComparison.OrdinalIgnoreCase))
  291. return GZip(bytes);
  292. throw new NotSupportedException(compressionType);
  293. }
  294. private byte[] CompressBrotli(byte[] bytes)
  295. {
  296. return _brotliCompressor.Compress(bytes);
  297. }
  298. private byte[] Deflate(byte[] bytes)
  299. {
  300. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  301. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  302. using (var ms = new MemoryStream())
  303. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  304. {
  305. zipStream.Write(bytes, 0, bytes.Length);
  306. zipStream.Dispose();
  307. return ms.ToArray();
  308. }
  309. }
  310. private byte[] GZip(byte[] buffer)
  311. {
  312. using (var ms = new MemoryStream())
  313. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  314. {
  315. zipStream.Write(buffer, 0, buffer.Length);
  316. zipStream.Dispose();
  317. return ms.ToArray();
  318. }
  319. }
  320. public static string GetRealContentType(string contentType)
  321. {
  322. return contentType == null
  323. ? null
  324. : contentType.Split(';')[0].ToLower().Trim();
  325. }
  326. private 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. var reader = new StreamReader(ms);
  340. return reader.ReadToEnd();
  341. }
  342. }
  343. }
  344. /// <summary>
  345. /// Pres the process optimized result.
  346. /// </summary>
  347. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  348. {
  349. responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString);
  350. var noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
  351. if (!noCache)
  352. {
  353. if (IsNotModified(requestContext, cacheKey, lastDateModified, cacheDuration))
  354. {
  355. AddAgeHeader(responseHeaders, lastDateModified);
  356. AddExpiresHeader(responseHeaders, cacheKeyString, cacheDuration);
  357. var result = new HttpResult(Array.Empty<byte>(), contentType ?? "text/html", HttpStatusCode.NotModified);
  358. AddResponseHeaders(result, responseHeaders);
  359. return result;
  360. }
  361. }
  362. AddCachingHeaders(responseHeaders, cacheKeyString, lastDateModified, cacheDuration);
  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("path");
  372. }
  373. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  374. {
  375. Path = path,
  376. FileShare = fileShare
  377. });
  378. }
  379. public Task<object> GetStaticFileResult(IRequest requestContext,
  380. StaticFileResultOptions options)
  381. {
  382. var path = options.Path;
  383. var fileShare = options.FileShare;
  384. if (string.IsNullOrEmpty(path))
  385. {
  386. throw new ArgumentNullException("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. var cacheKey = path + options.DateLastModified.Value.Ticks;
  401. options.CacheKey = cacheKey.GetMD5();
  402. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  403. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  404. return GetStaticResult(requestContext, options);
  405. }
  406. /// <summary>
  407. /// Gets the file stream.
  408. /// </summary>
  409. /// <param name="path">The path.</param>
  410. /// <param name="fileShare">The file share.</param>
  411. /// <returns>Stream.</returns>
  412. private Stream GetFileStream(string path, FileShareMode fileShare)
  413. {
  414. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  415. }
  416. public Task<object> GetStaticResult(IRequest requestContext,
  417. Guid cacheKey,
  418. DateTime? lastDateModified,
  419. TimeSpan? cacheDuration,
  420. string contentType,
  421. Func<Task<Stream>> factoryFn,
  422. IDictionary<string, string> responseHeaders = null,
  423. bool isHeadRequest = false)
  424. {
  425. return GetStaticResult(requestContext, new StaticResultOptions
  426. {
  427. CacheDuration = cacheDuration,
  428. CacheKey = cacheKey,
  429. ContentFactory = factoryFn,
  430. ContentType = contentType,
  431. DateLastModified = lastDateModified,
  432. IsHeadRequest = isHeadRequest,
  433. ResponseHeaders = responseHeaders
  434. });
  435. }
  436. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  437. {
  438. var cacheKey = options.CacheKey;
  439. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  440. var contentType = options.ContentType;
  441. if (!cacheKey.Equals(Guid.Empty))
  442. {
  443. var key = cacheKey.ToString("N");
  444. // See if the result is already cached in the browser
  445. var result = GetCachedResult(requestContext, options.ResponseHeaders, cacheKey, key, options.DateLastModified, options.CacheDuration, contentType);
  446. if (result != null)
  447. {
  448. return result;
  449. }
  450. }
  451. // TODO: We don't really need the option value
  452. var isHeadRequest = options.IsHeadRequest || string.Equals(requestContext.Verb, "HEAD", StringComparison.OrdinalIgnoreCase);
  453. var factoryFn = options.ContentFactory;
  454. var responseHeaders = options.ResponseHeaders;
  455. //var requestedCompressionType = GetCompressionType(requestContext);
  456. var rangeHeader = requestContext.Headers.Get("Range");
  457. if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
  458. {
  459. var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
  460. {
  461. OnComplete = options.OnComplete,
  462. OnError = options.OnError,
  463. FileShare = options.FileShare
  464. };
  465. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  466. return hasHeaders;
  467. }
  468. var stream = await factoryFn().ConfigureAwait(false);
  469. var totalContentLength = options.ContentLength;
  470. if (!totalContentLength.HasValue)
  471. {
  472. try
  473. {
  474. totalContentLength = stream.Length;
  475. }
  476. catch (NotSupportedException)
  477. {
  478. }
  479. }
  480. if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue)
  481. {
  482. var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest, _logger)
  483. {
  484. OnComplete = options.OnComplete
  485. };
  486. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  487. return hasHeaders;
  488. }
  489. else
  490. {
  491. if (totalContentLength.HasValue)
  492. {
  493. responseHeaders["Content-Length"] = totalContentLength.Value.ToString(UsCulture);
  494. }
  495. if (isHeadRequest)
  496. {
  497. using (stream)
  498. {
  499. return GetHttpResult(requestContext, Array.Empty<byte>(), contentType, true, responseHeaders);
  500. }
  501. }
  502. var hasHeaders = new StreamWriter(stream, contentType, _logger)
  503. {
  504. OnComplete = options.OnComplete,
  505. OnError = options.OnError
  506. };
  507. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  508. return hasHeaders;
  509. }
  510. }
  511. /// <summary>
  512. /// The us culture
  513. /// </summary>
  514. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  515. /// <summary>
  516. /// Adds the caching responseHeaders.
  517. /// </summary>
  518. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  519. {
  520. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  521. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  522. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  523. {
  524. AddAgeHeader(responseHeaders, lastDateModified);
  525. responseHeaders["Last-Modified"] = lastDateModified.Value.ToString("r");
  526. }
  527. if (cacheDuration.HasValue)
  528. {
  529. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  530. }
  531. else if (!string.IsNullOrEmpty(cacheKey))
  532. {
  533. responseHeaders["Cache-Control"] = "public";
  534. }
  535. else
  536. {
  537. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  538. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  539. }
  540. AddExpiresHeader(responseHeaders, cacheKey, cacheDuration);
  541. }
  542. /// <summary>
  543. /// Adds the expires header.
  544. /// </summary>
  545. private void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration)
  546. {
  547. if (cacheDuration.HasValue)
  548. {
  549. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  550. }
  551. else if (string.IsNullOrEmpty(cacheKey))
  552. {
  553. responseHeaders["Expires"] = "-1";
  554. }
  555. }
  556. /// <summary>
  557. /// Adds the age header.
  558. /// </summary>
  559. /// <param name="responseHeaders">The responseHeaders.</param>
  560. /// <param name="lastDateModified">The last date modified.</param>
  561. private void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  562. {
  563. if (lastDateModified.HasValue)
  564. {
  565. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  566. }
  567. }
  568. /// <summary>
  569. /// Determines whether [is not modified] [the specified cache key].
  570. /// </summary>
  571. /// <param name="requestContext">The request context.</param>
  572. /// <param name="cacheKey">The cache key.</param>
  573. /// <param name="lastDateModified">The last date modified.</param>
  574. /// <param name="cacheDuration">Duration of the cache.</param>
  575. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  576. private bool IsNotModified(IRequest requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  577. {
  578. //var isNotModified = true;
  579. var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since");
  580. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  581. {
  582. DateTime ifModifiedSince;
  583. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  584. {
  585. if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  586. {
  587. return true;
  588. }
  589. }
  590. }
  591. var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match");
  592. var hasCacheKey = !cacheKey.Equals(Guid.Empty);
  593. // Validate If-None-Match
  594. if ((hasCacheKey || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  595. {
  596. Guid ifNoneMatch;
  597. ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"');
  598. if (Guid.TryParse(ifNoneMatchHeader, out ifNoneMatch))
  599. {
  600. if (hasCacheKey && cacheKey.Equals(ifNoneMatch))
  601. {
  602. return true;
  603. }
  604. }
  605. }
  606. return false;
  607. }
  608. /// <summary>
  609. /// Determines whether [is not modified] [the specified if modified since].
  610. /// </summary>
  611. /// <param name="ifModifiedSince">If modified since.</param>
  612. /// <param name="cacheDuration">Duration of the cache.</param>
  613. /// <param name="dateModified">The date modified.</param>
  614. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  615. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  616. {
  617. if (dateModified.HasValue)
  618. {
  619. var lastModified = NormalizeDateForComparison(dateModified.Value);
  620. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  621. return lastModified <= ifModifiedSince;
  622. }
  623. if (cacheDuration.HasValue)
  624. {
  625. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  626. if (DateTime.UtcNow < cacheExpirationDate)
  627. {
  628. return true;
  629. }
  630. }
  631. return false;
  632. }
  633. /// <summary>
  634. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  635. /// </summary>
  636. /// <param name="date">The date.</param>
  637. /// <returns>DateTime.</returns>
  638. private DateTime NormalizeDateForComparison(DateTime date)
  639. {
  640. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  641. }
  642. /// <summary>
  643. /// Adds the response headers.
  644. /// </summary>
  645. /// <param name="hasHeaders">The has options.</param>
  646. /// <param name="responseHeaders">The response headers.</param>
  647. private void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  648. {
  649. foreach (var item in responseHeaders)
  650. {
  651. hasHeaders.Headers[item.Key] = item.Value;
  652. }
  653. }
  654. }
  655. public interface IBrotliCompressor
  656. {
  657. byte[] Compress(byte[] content);
  658. }
  659. }