HttpResultFactory.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out var expires))
  86. {
  87. responseHeaders["Expires"] = "-1";
  88. }
  89. AddResponseHeaders(result, responseHeaders);
  90. return result;
  91. }
  92. /// <summary>
  93. /// Gets the HTTP result.
  94. /// </summary>
  95. private IHasHeaders GetHttpResult(IRequest requestContext, byte[] content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  96. {
  97. string compressionType = null;
  98. bool isHeadRequest = false;
  99. if (requestContext != null)
  100. {
  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. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out var expires))
  123. {
  124. responseHeaders["Expires"] = "-1";
  125. }
  126. AddResponseHeaders(result, responseHeaders);
  127. return result;
  128. }
  129. /// <summary>
  130. /// Gets the HTTP result.
  131. /// </summary>
  132. private IHasHeaders GetHttpResult(IRequest requestContext, string content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  133. {
  134. IHasHeaders result;
  135. var bytes = Encoding.UTF8.GetBytes(content);
  136. var compressionType = requestContext == null ? null : GetCompressionType(requestContext, bytes, contentType);
  137. var isHeadRequest = requestContext == null ? false : string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase);
  138. if (string.IsNullOrEmpty(compressionType))
  139. {
  140. var contentLength = bytes.Length;
  141. if (isHeadRequest)
  142. {
  143. bytes = Array.Empty<byte>();
  144. }
  145. result = new StreamWriter(bytes, contentType, contentLength, _logger);
  146. }
  147. else
  148. {
  149. result = GetCompressedResult(bytes, compressionType, responseHeaders, isHeadRequest, contentType);
  150. }
  151. if (responseHeaders == null)
  152. {
  153. responseHeaders = new Dictionary<string, string>();
  154. }
  155. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out var expires))
  156. {
  157. responseHeaders["Expires"] = "-1";
  158. }
  159. AddResponseHeaders(result, responseHeaders);
  160. return result;
  161. }
  162. /// <summary>
  163. /// Gets the optimized result.
  164. /// </summary>
  165. /// <typeparam name="T"></typeparam>
  166. public object GetResult<T>(IRequest requestContext, T result, IDictionary<string, string> responseHeaders = null)
  167. where T : class
  168. {
  169. if (result == null)
  170. {
  171. throw new ArgumentNullException(nameof(result));
  172. }
  173. if (responseHeaders == null)
  174. {
  175. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  176. }
  177. responseHeaders["Expires"] = "-1";
  178. return ToOptimizedResultInternal(requestContext, result, responseHeaders);
  179. }
  180. private string GetCompressionType(IRequest request, byte[] content, string responseContentType)
  181. {
  182. if (responseContentType == null)
  183. {
  184. return null;
  185. }
  186. // Per apple docs, hls manifests must be compressed
  187. if (!responseContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) &&
  188. responseContentType.IndexOf("json", StringComparison.OrdinalIgnoreCase) == -1 &&
  189. responseContentType.IndexOf("javascript", StringComparison.OrdinalIgnoreCase) == -1 &&
  190. responseContentType.IndexOf("xml", StringComparison.OrdinalIgnoreCase) == -1 &&
  191. responseContentType.IndexOf("application/x-mpegURL", StringComparison.OrdinalIgnoreCase) == -1)
  192. {
  193. return null;
  194. }
  195. if (content.Length < 1024)
  196. {
  197. return null;
  198. }
  199. return GetCompressionType(request);
  200. }
  201. private static string GetCompressionType(IRequest request)
  202. {
  203. var acceptEncoding = request.Headers["Accept-Encoding"];
  204. if (acceptEncoding != null)
  205. {
  206. //if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
  207. // return "br";
  208. if (acceptEncoding.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
  209. return "deflate";
  210. if (acceptEncoding.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
  211. return "gzip";
  212. }
  213. return null;
  214. }
  215. /// <summary>
  216. /// Returns the optimized result for the IRequestContext.
  217. /// Does not use or store results in any cache.
  218. /// </summary>
  219. /// <param name="request"></param>
  220. /// <param name="dto"></param>
  221. /// <returns></returns>
  222. public object ToOptimizedResult<T>(IRequest request, T dto)
  223. {
  224. return ToOptimizedResultInternal(request, dto);
  225. }
  226. private object ToOptimizedResultInternal<T>(IRequest request, T dto, IDictionary<string, string> responseHeaders = null)
  227. {
  228. var contentType = request.ResponseContentType;
  229. switch (GetRealContentType(contentType))
  230. {
  231. case "application/xml":
  232. case "text/xml":
  233. case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
  234. return GetHttpResult(request, SerializeToXmlString(dto), contentType, false, responseHeaders);
  235. case "application/json":
  236. case "text/json":
  237. return GetHttpResult(request, _jsonSerializer.SerializeToString(dto), contentType, false, responseHeaders);
  238. default:
  239. break;
  240. }
  241. var isHeadRequest = string.Equals(request.Verb, "head", StringComparison.OrdinalIgnoreCase);
  242. var ms = new MemoryStream();
  243. var writerFn = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
  244. writerFn(dto, ms);
  245. ms.Position = 0;
  246. if (isHeadRequest)
  247. {
  248. using (ms)
  249. {
  250. return GetHttpResult(request, Array.Empty<byte>(), contentType, true, responseHeaders);
  251. }
  252. }
  253. return GetHttpResult(request, ms, contentType, true, responseHeaders);
  254. }
  255. private IHasHeaders GetCompressedResult(byte[] content,
  256. string requestedCompressionType,
  257. IDictionary<string, string> responseHeaders,
  258. bool isHeadRequest,
  259. string contentType)
  260. {
  261. if (responseHeaders == null)
  262. {
  263. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  264. }
  265. content = Compress(content, requestedCompressionType);
  266. responseHeaders["Content-Encoding"] = requestedCompressionType;
  267. responseHeaders["Vary"] = "Accept-Encoding";
  268. var contentLength = content.Length;
  269. if (isHeadRequest)
  270. {
  271. var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength, _logger);
  272. AddResponseHeaders(result, responseHeaders);
  273. return result;
  274. }
  275. else
  276. {
  277. var result = new StreamWriter(content, contentType, contentLength, _logger);
  278. AddResponseHeaders(result, responseHeaders);
  279. return result;
  280. }
  281. }
  282. private byte[] Compress(byte[] bytes, string compressionType)
  283. {
  284. if (string.Equals(compressionType, "br", StringComparison.OrdinalIgnoreCase))
  285. return CompressBrotli(bytes);
  286. if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
  287. return Deflate(bytes);
  288. if (string.Equals(compressionType, "gzip", StringComparison.OrdinalIgnoreCase))
  289. return GZip(bytes);
  290. throw new NotSupportedException(compressionType);
  291. }
  292. private byte[] CompressBrotli(byte[] bytes)
  293. {
  294. return _brotliCompressor.Compress(bytes);
  295. }
  296. private static byte[] Deflate(byte[] bytes)
  297. {
  298. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  299. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  300. using (var ms = new MemoryStream())
  301. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  302. {
  303. zipStream.Write(bytes, 0, bytes.Length);
  304. zipStream.Dispose();
  305. return ms.ToArray();
  306. }
  307. }
  308. private static byte[] GZip(byte[] buffer)
  309. {
  310. using (var ms = new MemoryStream())
  311. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  312. {
  313. zipStream.Write(buffer, 0, buffer.Length);
  314. zipStream.Dispose();
  315. return ms.ToArray();
  316. }
  317. }
  318. public static string GetRealContentType(string contentType)
  319. {
  320. return contentType == null
  321. ? null
  322. : contentType.Split(';')[0].ToLower().Trim();
  323. }
  324. private static string SerializeToXmlString(object from)
  325. {
  326. using (var ms = new MemoryStream())
  327. {
  328. var xwSettings = new XmlWriterSettings();
  329. xwSettings.Encoding = new UTF8Encoding(false);
  330. xwSettings.OmitXmlDeclaration = false;
  331. using (var xw = XmlWriter.Create(ms, xwSettings))
  332. {
  333. var serializer = new DataContractSerializer(from.GetType());
  334. serializer.WriteObject(xw, from);
  335. xw.Flush();
  336. ms.Seek(0, SeekOrigin.Begin);
  337. var reader = new StreamReader(ms);
  338. return reader.ReadToEnd();
  339. }
  340. }
  341. }
  342. /// <summary>
  343. /// Pres the process optimized result.
  344. /// </summary>
  345. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  346. {
  347. responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString);
  348. var noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
  349. if (!noCache)
  350. {
  351. if (IsNotModified(requestContext, cacheKey, lastDateModified, cacheDuration))
  352. {
  353. AddAgeHeader(responseHeaders, lastDateModified);
  354. AddExpiresHeader(responseHeaders, cacheKeyString, cacheDuration);
  355. var result = new HttpResult(Array.Empty<byte>(), contentType ?? "text/html", HttpStatusCode.NotModified);
  356. AddResponseHeaders(result, responseHeaders);
  357. return result;
  358. }
  359. }
  360. AddCachingHeaders(responseHeaders, cacheKeyString, lastDateModified, cacheDuration);
  361. return null;
  362. }
  363. public Task<object> GetStaticFileResult(IRequest requestContext,
  364. string path,
  365. FileShareMode fileShare = FileShareMode.Read)
  366. {
  367. if (string.IsNullOrEmpty(path))
  368. {
  369. throw new ArgumentNullException(nameof(path));
  370. }
  371. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  372. {
  373. Path = path,
  374. FileShare = fileShare
  375. });
  376. }
  377. public Task<object> GetStaticFileResult(IRequest requestContext,
  378. StaticFileResultOptions options)
  379. {
  380. var path = options.Path;
  381. var fileShare = options.FileShare;
  382. if (string.IsNullOrEmpty(path))
  383. {
  384. throw new ArgumentNullException(nameof(path));
  385. }
  386. if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
  387. {
  388. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  389. }
  390. if (string.IsNullOrEmpty(options.ContentType))
  391. {
  392. options.ContentType = MimeTypes.GetMimeType(path);
  393. }
  394. if (!options.DateLastModified.HasValue)
  395. {
  396. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  397. }
  398. var cacheKey = path + options.DateLastModified.Value.Ticks;
  399. options.CacheKey = cacheKey.GetMD5();
  400. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  401. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  402. return GetStaticResult(requestContext, options);
  403. }
  404. /// <summary>
  405. /// Gets the file stream.
  406. /// </summary>
  407. /// <param name="path">The path.</param>
  408. /// <param name="fileShare">The file share.</param>
  409. /// <returns>Stream.</returns>
  410. private Stream GetFileStream(string path, FileShareMode fileShare)
  411. {
  412. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  413. }
  414. public Task<object> GetStaticResult(IRequest requestContext,
  415. Guid cacheKey,
  416. DateTime? lastDateModified,
  417. TimeSpan? cacheDuration,
  418. string contentType,
  419. Func<Task<Stream>> factoryFn,
  420. IDictionary<string, string> responseHeaders = null,
  421. bool isHeadRequest = false)
  422. {
  423. return GetStaticResult(requestContext, new StaticResultOptions
  424. {
  425. CacheDuration = cacheDuration,
  426. CacheKey = cacheKey,
  427. ContentFactory = factoryFn,
  428. ContentType = contentType,
  429. DateLastModified = lastDateModified,
  430. IsHeadRequest = isHeadRequest,
  431. ResponseHeaders = responseHeaders
  432. });
  433. }
  434. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  435. {
  436. var cacheKey = options.CacheKey;
  437. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  438. var contentType = options.ContentType;
  439. if (!cacheKey.Equals(Guid.Empty))
  440. {
  441. var key = cacheKey.ToString("N");
  442. // See if the result is already cached in the browser
  443. var result = GetCachedResult(requestContext, options.ResponseHeaders, cacheKey, key, options.DateLastModified, options.CacheDuration, contentType);
  444. if (result != null)
  445. {
  446. return result;
  447. }
  448. }
  449. // TODO: We don't really need the option value
  450. var isHeadRequest = options.IsHeadRequest || string.Equals(requestContext.Verb, "HEAD", StringComparison.OrdinalIgnoreCase);
  451. var factoryFn = options.ContentFactory;
  452. var responseHeaders = options.ResponseHeaders;
  453. //var requestedCompressionType = GetCompressionType(requestContext);
  454. var rangeHeader = requestContext.Headers.Get("Range");
  455. if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
  456. {
  457. var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
  458. {
  459. OnComplete = options.OnComplete,
  460. OnError = options.OnError,
  461. FileShare = options.FileShare
  462. };
  463. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  464. return hasHeaders;
  465. }
  466. var stream = await factoryFn().ConfigureAwait(false);
  467. var totalContentLength = options.ContentLength;
  468. if (!totalContentLength.HasValue)
  469. {
  470. try
  471. {
  472. totalContentLength = stream.Length;
  473. }
  474. catch (NotSupportedException)
  475. {
  476. }
  477. }
  478. if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue)
  479. {
  480. var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest, _logger)
  481. {
  482. OnComplete = options.OnComplete
  483. };
  484. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  485. return hasHeaders;
  486. }
  487. else
  488. {
  489. if (totalContentLength.HasValue)
  490. {
  491. responseHeaders["Content-Length"] = totalContentLength.Value.ToString(UsCulture);
  492. }
  493. if (isHeadRequest)
  494. {
  495. using (stream)
  496. {
  497. return GetHttpResult(requestContext, Array.Empty<byte>(), contentType, true, responseHeaders);
  498. }
  499. }
  500. var hasHeaders = new StreamWriter(stream, contentType, _logger)
  501. {
  502. OnComplete = options.OnComplete,
  503. OnError = options.OnError
  504. };
  505. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  506. return hasHeaders;
  507. }
  508. }
  509. /// <summary>
  510. /// The us culture
  511. /// </summary>
  512. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  513. /// <summary>
  514. /// Adds the caching responseHeaders.
  515. /// </summary>
  516. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  517. {
  518. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  519. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  520. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  521. {
  522. AddAgeHeader(responseHeaders, lastDateModified);
  523. responseHeaders["Last-Modified"] = lastDateModified.Value.ToString("r");
  524. }
  525. if (cacheDuration.HasValue)
  526. {
  527. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  528. }
  529. else if (!string.IsNullOrEmpty(cacheKey))
  530. {
  531. responseHeaders["Cache-Control"] = "public";
  532. }
  533. else
  534. {
  535. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  536. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  537. }
  538. AddExpiresHeader(responseHeaders, cacheKey, cacheDuration);
  539. }
  540. /// <summary>
  541. /// Adds the expires header.
  542. /// </summary>
  543. private static void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration)
  544. {
  545. if (cacheDuration.HasValue)
  546. {
  547. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  548. }
  549. else if (string.IsNullOrEmpty(cacheKey))
  550. {
  551. responseHeaders["Expires"] = "-1";
  552. }
  553. }
  554. /// <summary>
  555. /// Adds the age header.
  556. /// </summary>
  557. /// <param name="responseHeaders">The responseHeaders.</param>
  558. /// <param name="lastDateModified">The last date modified.</param>
  559. private static void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  560. {
  561. if (lastDateModified.HasValue)
  562. {
  563. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  564. }
  565. }
  566. /// <summary>
  567. /// Determines whether [is not modified] [the specified cache key].
  568. /// </summary>
  569. /// <param name="requestContext">The request context.</param>
  570. /// <param name="cacheKey">The cache key.</param>
  571. /// <param name="lastDateModified">The last date modified.</param>
  572. /// <param name="cacheDuration">Duration of the cache.</param>
  573. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  574. private bool IsNotModified(IRequest requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  575. {
  576. //var isNotModified = true;
  577. var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since");
  578. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  579. {
  580. if (DateTime.TryParse(ifModifiedSinceHeader, out var ifModifiedSince))
  581. {
  582. if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  583. {
  584. return true;
  585. }
  586. }
  587. }
  588. var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match");
  589. var hasCacheKey = !cacheKey.Equals(Guid.Empty);
  590. // Validate If-None-Match
  591. if ((hasCacheKey || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  592. {
  593. ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"');
  594. if (Guid.TryParse(ifNoneMatchHeader, out var ifNoneMatch))
  595. {
  596. if (hasCacheKey && cacheKey.Equals(ifNoneMatch))
  597. {
  598. return true;
  599. }
  600. }
  601. }
  602. return false;
  603. }
  604. /// <summary>
  605. /// Determines whether [is not modified] [the specified if modified since].
  606. /// </summary>
  607. /// <param name="ifModifiedSince">If modified since.</param>
  608. /// <param name="cacheDuration">Duration of the cache.</param>
  609. /// <param name="dateModified">The date modified.</param>
  610. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  611. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  612. {
  613. if (dateModified.HasValue)
  614. {
  615. var lastModified = NormalizeDateForComparison(dateModified.Value);
  616. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  617. return lastModified <= ifModifiedSince;
  618. }
  619. if (cacheDuration.HasValue)
  620. {
  621. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  622. if (DateTime.UtcNow < cacheExpirationDate)
  623. {
  624. return true;
  625. }
  626. }
  627. return false;
  628. }
  629. /// <summary>
  630. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  631. /// </summary>
  632. /// <param name="date">The date.</param>
  633. /// <returns>DateTime.</returns>
  634. private static DateTime NormalizeDateForComparison(DateTime date)
  635. {
  636. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  637. }
  638. /// <summary>
  639. /// Adds the response headers.
  640. /// </summary>
  641. /// <param name="hasHeaders">The has options.</param>
  642. /// <param name="responseHeaders">The response headers.</param>
  643. private static void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  644. {
  645. foreach (var item in responseHeaders)
  646. {
  647. hasHeaders.Headers[item.Key] = item.Value;
  648. }
  649. }
  650. }
  651. public interface IBrotliCompressor
  652. {
  653. byte[] Compress(byte[] content);
  654. }
  655. }