HttpResultFactory.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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(nameof(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 static 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 static 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 static 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 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, Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  350. {
  351. responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString);
  352. bool noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
  353. if (!noCache)
  354. {
  355. if (IsNotModified(requestContext, cacheKey, lastDateModified, cacheDuration))
  356. {
  357. AddAgeHeader(responseHeaders, lastDateModified);
  358. AddExpiresHeader(responseHeaders, cacheKeyString, cacheDuration);
  359. var result = new HttpResult(Array.Empty<byte>(), contentType ?? "text/html", HttpStatusCode.NotModified);
  360. AddResponseHeaders(result, responseHeaders);
  361. return result;
  362. }
  363. }
  364. AddCachingHeaders(responseHeaders, cacheKeyString, lastDateModified, cacheDuration);
  365. return null;
  366. }
  367. public Task<object> GetStaticFileResult(IRequest requestContext,
  368. string path,
  369. FileShareMode fileShare = FileShareMode.Read)
  370. {
  371. if (string.IsNullOrEmpty(path))
  372. {
  373. throw new ArgumentNullException(nameof(path));
  374. }
  375. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  376. {
  377. Path = path,
  378. FileShare = fileShare
  379. });
  380. }
  381. public Task<object> GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options)
  382. {
  383. var path = options.Path;
  384. var fileShare = options.FileShare;
  385. if (string.IsNullOrEmpty(path))
  386. {
  387. throw new ArgumentNullException(nameof(path));
  388. }
  389. if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
  390. {
  391. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  392. }
  393. if (string.IsNullOrEmpty(options.ContentType))
  394. {
  395. options.ContentType = MimeTypes.GetMimeType(path);
  396. }
  397. if (!options.DateLastModified.HasValue)
  398. {
  399. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  400. }
  401. var cacheKey = path + options.DateLastModified.Value.Ticks;
  402. options.CacheKey = cacheKey.GetMD5();
  403. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  404. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  405. return GetStaticResult(requestContext, options);
  406. }
  407. /// <summary>
  408. /// Gets the file stream.
  409. /// </summary>
  410. /// <param name="path">The path.</param>
  411. /// <param name="fileShare">The file share.</param>
  412. /// <returns>Stream.</returns>
  413. private Stream GetFileStream(string path, FileShareMode fileShare)
  414. {
  415. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  416. }
  417. public Task<object> GetStaticResult(IRequest requestContext,
  418. Guid cacheKey,
  419. DateTime? lastDateModified,
  420. TimeSpan? cacheDuration,
  421. string contentType,
  422. Func<Task<Stream>> factoryFn,
  423. IDictionary<string, string> responseHeaders = null,
  424. bool isHeadRequest = false)
  425. {
  426. return GetStaticResult(requestContext, new StaticResultOptions
  427. {
  428. CacheDuration = cacheDuration,
  429. CacheKey = cacheKey,
  430. ContentFactory = factoryFn,
  431. ContentType = contentType,
  432. DateLastModified = lastDateModified,
  433. IsHeadRequest = isHeadRequest,
  434. ResponseHeaders = responseHeaders
  435. });
  436. }
  437. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  438. {
  439. var cacheKey = options.CacheKey;
  440. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  441. var contentType = options.ContentType;
  442. if (!cacheKey.Equals(Guid.Empty))
  443. {
  444. var key = cacheKey.ToString("N");
  445. // See if the result is already cached in the browser
  446. var result = GetCachedResult(requestContext, options.ResponseHeaders, cacheKey, key, options.DateLastModified, options.CacheDuration, contentType);
  447. if (result != null)
  448. {
  449. return result;
  450. }
  451. }
  452. // TODO: We don't really need the option value
  453. var isHeadRequest = options.IsHeadRequest || string.Equals(requestContext.Verb, "HEAD", StringComparison.OrdinalIgnoreCase);
  454. var factoryFn = options.ContentFactory;
  455. var responseHeaders = options.ResponseHeaders;
  456. //var requestedCompressionType = GetCompressionType(requestContext);
  457. var rangeHeader = requestContext.Headers.Get("Range");
  458. if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
  459. {
  460. var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
  461. {
  462. OnComplete = options.OnComplete,
  463. OnError = options.OnError,
  464. FileShare = options.FileShare
  465. };
  466. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  467. return hasHeaders;
  468. }
  469. var stream = await factoryFn().ConfigureAwait(false);
  470. var totalContentLength = options.ContentLength;
  471. if (!totalContentLength.HasValue)
  472. {
  473. try
  474. {
  475. totalContentLength = stream.Length;
  476. }
  477. catch (NotSupportedException)
  478. {
  479. }
  480. }
  481. if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue)
  482. {
  483. var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest, _logger)
  484. {
  485. OnComplete = options.OnComplete
  486. };
  487. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  488. return hasHeaders;
  489. }
  490. else
  491. {
  492. if (totalContentLength.HasValue)
  493. {
  494. responseHeaders["Content-Length"] = totalContentLength.Value.ToString(UsCulture);
  495. }
  496. if (isHeadRequest)
  497. {
  498. using (stream)
  499. {
  500. return GetHttpResult(requestContext, Array.Empty<byte>(), contentType, true, responseHeaders);
  501. }
  502. }
  503. var hasHeaders = new StreamWriter(stream, contentType, _logger)
  504. {
  505. OnComplete = options.OnComplete,
  506. OnError = options.OnError
  507. };
  508. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  509. return hasHeaders;
  510. }
  511. }
  512. /// <summary>
  513. /// The us culture
  514. /// </summary>
  515. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  516. /// <summary>
  517. /// Adds the caching responseHeaders.
  518. /// </summary>
  519. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  520. {
  521. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  522. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  523. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  524. {
  525. AddAgeHeader(responseHeaders, lastDateModified);
  526. responseHeaders["Last-Modified"] = lastDateModified.Value.ToString("r");
  527. }
  528. if (cacheDuration.HasValue)
  529. {
  530. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  531. }
  532. else if (!string.IsNullOrEmpty(cacheKey))
  533. {
  534. responseHeaders["Cache-Control"] = "public";
  535. }
  536. else
  537. {
  538. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  539. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  540. }
  541. AddExpiresHeader(responseHeaders, cacheKey, cacheDuration);
  542. }
  543. /// <summary>
  544. /// Adds the expires header.
  545. /// </summary>
  546. private static void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration)
  547. {
  548. if (cacheDuration.HasValue)
  549. {
  550. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  551. }
  552. else if (string.IsNullOrEmpty(cacheKey))
  553. {
  554. responseHeaders["Expires"] = "-1";
  555. }
  556. }
  557. /// <summary>
  558. /// Adds the age header.
  559. /// </summary>
  560. /// <param name="responseHeaders">The responseHeaders.</param>
  561. /// <param name="lastDateModified">The last date modified.</param>
  562. private static void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  563. {
  564. if (lastDateModified.HasValue)
  565. {
  566. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  567. }
  568. }
  569. /// <summary>
  570. /// Determines whether [is not modified] [the specified cache key].
  571. /// </summary>
  572. /// <param name="requestContext">The request context.</param>
  573. /// <param name="cacheKey">The cache key.</param>
  574. /// <param name="lastDateModified">The last date modified.</param>
  575. /// <param name="cacheDuration">Duration of the cache.</param>
  576. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  577. private bool IsNotModified(IRequest requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  578. {
  579. //var isNotModified = true;
  580. var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since");
  581. if (!string.IsNullOrEmpty(ifModifiedSinceHeader)
  582. && DateTime.TryParse(ifModifiedSinceHeader, out DateTime ifModifiedSince)
  583. && IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  584. {
  585. return true;
  586. }
  587. var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match");
  588. bool hasCacheKey = !cacheKey.Equals(Guid.Empty);
  589. // Validate If-None-Match
  590. if ((hasCacheKey && !string.IsNullOrEmpty(ifNoneMatchHeader)))
  591. {
  592. ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"');
  593. if (Guid.TryParse(ifNoneMatchHeader, out Guid ifNoneMatch)
  594. && cacheKey.Equals(ifNoneMatch))
  595. {
  596. return true;
  597. }
  598. }
  599. return false;
  600. }
  601. /// <summary>
  602. /// Determines whether [is not modified] [the specified if modified since].
  603. /// </summary>
  604. /// <param name="ifModifiedSince">If modified since.</param>
  605. /// <param name="cacheDuration">Duration of the cache.</param>
  606. /// <param name="dateModified">The date modified.</param>
  607. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  608. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  609. {
  610. if (dateModified.HasValue)
  611. {
  612. var lastModified = NormalizeDateForComparison(dateModified.Value);
  613. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  614. return lastModified <= ifModifiedSince;
  615. }
  616. if (cacheDuration.HasValue)
  617. {
  618. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  619. if (DateTime.UtcNow < cacheExpirationDate)
  620. {
  621. return true;
  622. }
  623. }
  624. return false;
  625. }
  626. /// <summary>
  627. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  628. /// </summary>
  629. /// <param name="date">The date.</param>
  630. /// <returns>DateTime.</returns>
  631. private static DateTime NormalizeDateForComparison(DateTime date)
  632. {
  633. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  634. }
  635. /// <summary>
  636. /// Adds the response headers.
  637. /// </summary>
  638. /// <param name="hasHeaders">The has options.</param>
  639. /// <param name="responseHeaders">The response headers.</param>
  640. private static void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  641. {
  642. foreach (var item in responseHeaders)
  643. {
  644. hasHeaders.Headers[item.Key] = item.Value;
  645. }
  646. }
  647. }
  648. public interface IBrotliCompressor
  649. {
  650. byte[] Compress(byte[] content);
  651. }
  652. }