2
0

HttpResultFactory.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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.Text;
  9. using System.Threading.Tasks;
  10. using System.Xml;
  11. using Emby.Server.Implementations.Services;
  12. using MediaBrowser.Common.Extensions;
  13. using MediaBrowser.Controller.Net;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.Serialization;
  16. using MediaBrowser.Model.Services;
  17. using Microsoft.Extensions.Logging;
  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. {
  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. string expires;
  124. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out expires))
  125. {
  126. responseHeaders["Expires"] = "-1";
  127. }
  128. AddResponseHeaders(result, responseHeaders);
  129. return result;
  130. }
  131. /// <summary>
  132. /// Gets the HTTP result.
  133. /// </summary>
  134. private IHasHeaders GetHttpResult(IRequest requestContext, string content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  135. {
  136. IHasHeaders result;
  137. var bytes = Encoding.UTF8.GetBytes(content);
  138. var compressionType = requestContext == null ? null : GetCompressionType(requestContext, bytes, contentType);
  139. var isHeadRequest = requestContext == null ? false : string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase);
  140. if (string.IsNullOrEmpty(compressionType))
  141. {
  142. var contentLength = bytes.Length;
  143. if (isHeadRequest)
  144. {
  145. bytes = Array.Empty<byte>();
  146. }
  147. result = new StreamWriter(bytes, contentType, contentLength, _logger);
  148. }
  149. else
  150. {
  151. result = GetCompressedResult(bytes, compressionType, responseHeaders, isHeadRequest, contentType);
  152. }
  153. if (responseHeaders == null)
  154. {
  155. responseHeaders = new Dictionary<string, string>();
  156. }
  157. string expires;
  158. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out expires))
  159. {
  160. responseHeaders["Expires"] = "-1";
  161. }
  162. AddResponseHeaders(result, responseHeaders);
  163. return result;
  164. }
  165. /// <summary>
  166. /// Gets the optimized result.
  167. /// </summary>
  168. /// <typeparam name="T"></typeparam>
  169. public object GetResult<T>(IRequest requestContext, T result, IDictionary<string, string> responseHeaders = null)
  170. where T : class
  171. {
  172. if (result == null)
  173. {
  174. throw new ArgumentNullException(nameof(result));
  175. }
  176. if (responseHeaders == null)
  177. {
  178. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  179. }
  180. responseHeaders["Expires"] = "-1";
  181. return ToOptimizedResultInternal(requestContext, result, responseHeaders);
  182. }
  183. private string GetCompressionType(IRequest request, byte[] content, string responseContentType)
  184. {
  185. if (responseContentType == null)
  186. {
  187. return null;
  188. }
  189. // Per apple docs, hls manifests must be compressed
  190. if (!responseContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) &&
  191. responseContentType.IndexOf("json", StringComparison.OrdinalIgnoreCase) == -1 &&
  192. responseContentType.IndexOf("javascript", StringComparison.OrdinalIgnoreCase) == -1 &&
  193. responseContentType.IndexOf("xml", StringComparison.OrdinalIgnoreCase) == -1 &&
  194. responseContentType.IndexOf("application/x-mpegURL", StringComparison.OrdinalIgnoreCase) == -1)
  195. {
  196. return null;
  197. }
  198. if (content.Length < 1024)
  199. {
  200. return null;
  201. }
  202. return GetCompressionType(request);
  203. }
  204. private static string GetCompressionType(IRequest request)
  205. {
  206. var acceptEncoding = request.Headers["Accept-Encoding"];
  207. if (acceptEncoding != null)
  208. {
  209. //if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
  210. // return "br";
  211. if (acceptEncoding.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
  212. return "deflate";
  213. if (acceptEncoding.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
  214. return "gzip";
  215. }
  216. return null;
  217. }
  218. /// <summary>
  219. /// Returns the optimized result for the IRequestContext.
  220. /// Does not use or store results in any cache.
  221. /// </summary>
  222. /// <param name="request"></param>
  223. /// <param name="dto"></param>
  224. /// <returns></returns>
  225. public object ToOptimizedResult<T>(IRequest request, T dto)
  226. {
  227. return ToOptimizedResultInternal(request, dto);
  228. }
  229. private object ToOptimizedResultInternal<T>(IRequest request, T dto, IDictionary<string, string> responseHeaders = null)
  230. {
  231. var contentType = request.ResponseContentType;
  232. switch (GetRealContentType(contentType))
  233. {
  234. case "application/xml":
  235. case "text/xml":
  236. case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
  237. return GetHttpResult(request, SerializeToXmlString(dto), contentType, false, responseHeaders);
  238. case "application/json":
  239. case "text/json":
  240. return GetHttpResult(request, _jsonSerializer.SerializeToString(dto), contentType, false, responseHeaders);
  241. default:
  242. break;
  243. }
  244. var isHeadRequest = string.Equals(request.Verb, "head", StringComparison.OrdinalIgnoreCase);
  245. var ms = new MemoryStream();
  246. var writerFn = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
  247. writerFn(dto, ms);
  248. ms.Position = 0;
  249. if (isHeadRequest)
  250. {
  251. using (ms)
  252. {
  253. return GetHttpResult(request, Array.Empty<byte>(), contentType, true, responseHeaders);
  254. }
  255. }
  256. return GetHttpResult(request, ms, contentType, true, responseHeaders);
  257. }
  258. private IHasHeaders GetCompressedResult(byte[] content,
  259. string requestedCompressionType,
  260. IDictionary<string, string> responseHeaders,
  261. bool isHeadRequest,
  262. string contentType)
  263. {
  264. if (responseHeaders == null)
  265. {
  266. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  267. }
  268. content = Compress(content, requestedCompressionType);
  269. responseHeaders["Content-Encoding"] = requestedCompressionType;
  270. responseHeaders["Vary"] = "Accept-Encoding";
  271. var contentLength = content.Length;
  272. if (isHeadRequest)
  273. {
  274. var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength, _logger);
  275. AddResponseHeaders(result, responseHeaders);
  276. return result;
  277. }
  278. else
  279. {
  280. var result = new StreamWriter(content, contentType, contentLength, _logger);
  281. AddResponseHeaders(result, responseHeaders);
  282. return result;
  283. }
  284. }
  285. private byte[] Compress(byte[] bytes, string compressionType)
  286. {
  287. if (string.Equals(compressionType, "br", StringComparison.OrdinalIgnoreCase))
  288. return CompressBrotli(bytes);
  289. if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
  290. return Deflate(bytes);
  291. if (string.Equals(compressionType, "gzip", StringComparison.OrdinalIgnoreCase))
  292. return GZip(bytes);
  293. throw new NotSupportedException(compressionType);
  294. }
  295. private byte[] CompressBrotli(byte[] bytes)
  296. {
  297. return _brotliCompressor.Compress(bytes);
  298. }
  299. private static byte[] Deflate(byte[] bytes)
  300. {
  301. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  302. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  303. using (var ms = new MemoryStream())
  304. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  305. {
  306. zipStream.Write(bytes, 0, bytes.Length);
  307. zipStream.Dispose();
  308. return ms.ToArray();
  309. }
  310. }
  311. private static byte[] GZip(byte[] buffer)
  312. {
  313. using (var ms = new MemoryStream())
  314. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  315. {
  316. zipStream.Write(buffer, 0, buffer.Length);
  317. zipStream.Dispose();
  318. return ms.ToArray();
  319. }
  320. }
  321. public static string GetRealContentType(string contentType)
  322. {
  323. return contentType == null
  324. ? null
  325. : contentType.Split(';')[0].ToLower().Trim();
  326. }
  327. private static string SerializeToXmlString(object from)
  328. {
  329. using (var ms = new MemoryStream())
  330. {
  331. var xwSettings = new XmlWriterSettings();
  332. xwSettings.Encoding = new UTF8Encoding(false);
  333. xwSettings.OmitXmlDeclaration = false;
  334. using (var xw = XmlWriter.Create(ms, xwSettings))
  335. {
  336. var serializer = new DataContractSerializer(from.GetType());
  337. serializer.WriteObject(xw, from);
  338. xw.Flush();
  339. ms.Seek(0, SeekOrigin.Begin);
  340. var reader = new StreamReader(ms);
  341. return reader.ReadToEnd();
  342. }
  343. }
  344. }
  345. /// <summary>
  346. /// Pres the process optimized result.
  347. /// </summary>
  348. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  349. {
  350. responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString);
  351. var noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
  352. if (!noCache)
  353. {
  354. if (IsNotModified(requestContext, cacheKey, lastDateModified, cacheDuration))
  355. {
  356. AddAgeHeader(responseHeaders, lastDateModified);
  357. AddExpiresHeader(responseHeaders, cacheKeyString, cacheDuration);
  358. var result = new HttpResult(Array.Empty<byte>(), contentType ?? "text/html", HttpStatusCode.NotModified);
  359. AddResponseHeaders(result, responseHeaders);
  360. return result;
  361. }
  362. }
  363. AddCachingHeaders(responseHeaders, cacheKeyString, lastDateModified, cacheDuration);
  364. return null;
  365. }
  366. public Task<object> GetStaticFileResult(IRequest requestContext,
  367. string path,
  368. FileShareMode fileShare = FileShareMode.Read)
  369. {
  370. if (string.IsNullOrEmpty(path))
  371. {
  372. throw new ArgumentNullException(nameof(path));
  373. }
  374. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  375. {
  376. Path = path,
  377. FileShare = fileShare
  378. });
  379. }
  380. public Task<object> GetStaticFileResult(IRequest requestContext,
  381. 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. {
  583. DateTime ifModifiedSince;
  584. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  585. {
  586. if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  587. {
  588. return true;
  589. }
  590. }
  591. }
  592. var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match");
  593. var hasCacheKey = !cacheKey.Equals(Guid.Empty);
  594. // Validate If-None-Match
  595. if ((hasCacheKey || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  596. {
  597. Guid ifNoneMatch;
  598. ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"');
  599. if (Guid.TryParse(ifNoneMatchHeader, out ifNoneMatch))
  600. {
  601. if (hasCacheKey && cacheKey.Equals(ifNoneMatch))
  602. {
  603. return true;
  604. }
  605. }
  606. }
  607. return false;
  608. }
  609. /// <summary>
  610. /// Determines whether [is not modified] [the specified if modified since].
  611. /// </summary>
  612. /// <param name="ifModifiedSince">If modified since.</param>
  613. /// <param name="cacheDuration">Duration of the cache.</param>
  614. /// <param name="dateModified">The date modified.</param>
  615. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  616. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  617. {
  618. if (dateModified.HasValue)
  619. {
  620. var lastModified = NormalizeDateForComparison(dateModified.Value);
  621. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  622. return lastModified <= ifModifiedSince;
  623. }
  624. if (cacheDuration.HasValue)
  625. {
  626. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  627. if (DateTime.UtcNow < cacheExpirationDate)
  628. {
  629. return true;
  630. }
  631. }
  632. return false;
  633. }
  634. /// <summary>
  635. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  636. /// </summary>
  637. /// <param name="date">The date.</param>
  638. /// <returns>DateTime.</returns>
  639. private static DateTime NormalizeDateForComparison(DateTime date)
  640. {
  641. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  642. }
  643. /// <summary>
  644. /// Adds the response headers.
  645. /// </summary>
  646. /// <param name="hasHeaders">The has options.</param>
  647. /// <param name="responseHeaders">The response headers.</param>
  648. private static void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  649. {
  650. foreach (var item in responseHeaders)
  651. {
  652. hasHeaders.Headers[item.Key] = item.Value;
  653. }
  654. }
  655. }
  656. public interface IBrotliCompressor
  657. {
  658. byte[] Compress(byte[] content);
  659. }
  660. }