HttpResultFactory.cs 29 KB

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