HttpResultFactory.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Net;
  3. using MediaBrowser.Model.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.HttpServer;
  16. using Emby.Server.Implementations.Services;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.Services;
  19. using IRequest = MediaBrowser.Model.Services.IRequest;
  20. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  21. using StreamWriter = Emby.Server.Implementations.HttpServer.StreamWriter;
  22. namespace Emby.Server.Implementations.HttpServer
  23. {
  24. /// <summary>
  25. /// Class HttpResultFactory
  26. /// </summary>
  27. public class HttpResultFactory : IHttpResultFactory
  28. {
  29. /// <summary>
  30. /// The _logger
  31. /// </summary>
  32. private readonly ILogger _logger;
  33. private readonly IFileSystem _fileSystem;
  34. private readonly IJsonSerializer _jsonSerializer;
  35. private readonly IMemoryStreamFactory _memoryStreamFactory;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
  38. /// </summary>
  39. public HttpResultFactory(ILogManager logManager, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IMemoryStreamFactory memoryStreamFactory)
  40. {
  41. _fileSystem = fileSystem;
  42. _jsonSerializer = jsonSerializer;
  43. _memoryStreamFactory = memoryStreamFactory;
  44. _logger = logManager.GetLogger("HttpResultFactory");
  45. }
  46. /// <summary>
  47. /// Gets the result.
  48. /// </summary>
  49. /// <param name="content">The content.</param>
  50. /// <param name="contentType">Type of the content.</param>
  51. /// <param name="responseHeaders">The response headers.</param>
  52. /// <returns>System.Object.</returns>
  53. public object GetResult(object content, string contentType, IDictionary<string, string> responseHeaders = null)
  54. {
  55. return GetHttpResult(content, contentType, true, responseHeaders);
  56. }
  57. /// <summary>
  58. /// Gets the HTTP result.
  59. /// </summary>
  60. private IHasHeaders GetHttpResult(object content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  61. {
  62. IHasHeaders result;
  63. var stream = content as Stream;
  64. if (stream != null)
  65. {
  66. result = new StreamWriter(stream, contentType, _logger);
  67. }
  68. else
  69. {
  70. var bytes = content as byte[];
  71. if (bytes != null)
  72. {
  73. result = new StreamWriter(bytes, contentType, _logger);
  74. }
  75. else
  76. {
  77. var text = content as string;
  78. if (text != null)
  79. {
  80. result = new StreamWriter(Encoding.UTF8.GetBytes(text), contentType, _logger);
  81. }
  82. else
  83. {
  84. result = new HttpResult(content, contentType, HttpStatusCode.OK);
  85. }
  86. }
  87. }
  88. if (responseHeaders == null)
  89. {
  90. responseHeaders = new Dictionary<string, string>();
  91. }
  92. string expires;
  93. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out expires))
  94. {
  95. responseHeaders["Expires"] = "-1";
  96. }
  97. AddResponseHeaders(result, responseHeaders);
  98. return result;
  99. }
  100. /// <summary>
  101. /// Gets the optimized result.
  102. /// </summary>
  103. /// <typeparam name="T"></typeparam>
  104. /// <param name="requestContext">The request context.</param>
  105. /// <param name="result">The result.</param>
  106. /// <param name="responseHeaders">The response headers.</param>
  107. /// <returns>System.Object.</returns>
  108. /// <exception cref="System.ArgumentNullException">result</exception>
  109. public object GetOptimizedResult<T>(IRequest requestContext, T result, IDictionary<string, string> responseHeaders = null)
  110. where T : class
  111. {
  112. return GetOptimizedResultInternal<T>(requestContext, result, true, responseHeaders);
  113. }
  114. private object GetOptimizedResultInternal<T>(IRequest requestContext, T result, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  115. where T : class
  116. {
  117. if (result == null)
  118. {
  119. throw new ArgumentNullException("result");
  120. }
  121. var optimizedResult = ToOptimizedResult(requestContext, result);
  122. if (responseHeaders == null)
  123. {
  124. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  125. }
  126. if (addCachePrevention)
  127. {
  128. responseHeaders["Expires"] = "-1";
  129. }
  130. // Apply headers
  131. var hasHeaders = optimizedResult as IHasHeaders;
  132. if (hasHeaders != null)
  133. {
  134. AddResponseHeaders(hasHeaders, responseHeaders);
  135. }
  136. return optimizedResult;
  137. }
  138. public static string GetCompressionType(IRequest request)
  139. {
  140. var acceptEncoding = request.Headers["Accept-Encoding"];
  141. if (!string.IsNullOrWhiteSpace(acceptEncoding))
  142. {
  143. if (acceptEncoding.Contains("deflate"))
  144. return "deflate";
  145. if (acceptEncoding.Contains("gzip"))
  146. return "gzip";
  147. }
  148. return null;
  149. }
  150. /// <summary>
  151. /// Returns the optimized result for the IRequestContext.
  152. /// Does not use or store results in any cache.
  153. /// </summary>
  154. /// <param name="request"></param>
  155. /// <param name="dto"></param>
  156. /// <returns></returns>
  157. public object ToOptimizedResult<T>(IRequest request, T dto)
  158. {
  159. var compressionType = GetCompressionType(request);
  160. if (compressionType == null)
  161. {
  162. var contentType = request.ResponseContentType;
  163. switch (GetRealContentType(contentType))
  164. {
  165. case "application/xml":
  166. case "text/xml":
  167. case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
  168. return SerializeToXmlString(dto);
  169. case "application/json":
  170. case "text/json":
  171. return _jsonSerializer.SerializeToString(dto);
  172. }
  173. }
  174. // Do not use the memoryStreamFactory here, they don't place nice with compression
  175. using (var ms = new MemoryStream())
  176. {
  177. var contentType = request.ResponseContentType;
  178. var writerFn = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
  179. writerFn(dto, ms);
  180. ms.Position = 0;
  181. var responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  182. return GetCompressedResult(ms, compressionType, responseHeaders, false, request.ResponseContentType).Result;
  183. }
  184. }
  185. private static Stream GetCompressionStream(Stream outputStream, string compressionType)
  186. {
  187. if (compressionType == "deflate")
  188. return new DeflateStream(outputStream, CompressionMode.Compress, true);
  189. if (compressionType == "gzip")
  190. return new GZipStream(outputStream, CompressionMode.Compress, true);
  191. throw new NotSupportedException(compressionType);
  192. }
  193. public static string GetRealContentType(string contentType)
  194. {
  195. return contentType == null
  196. ? null
  197. : contentType.Split(';')[0].ToLower().Trim();
  198. }
  199. private string SerializeToXmlString(object from)
  200. {
  201. using (var ms = new MemoryStream())
  202. {
  203. var xwSettings = new XmlWriterSettings();
  204. xwSettings.Encoding = new UTF8Encoding(false);
  205. xwSettings.OmitXmlDeclaration = false;
  206. using (var xw = XmlWriter.Create(ms, xwSettings))
  207. {
  208. var serializer = new DataContractSerializer(from.GetType());
  209. serializer.WriteObject(xw, from);
  210. xw.Flush();
  211. ms.Seek(0, SeekOrigin.Begin);
  212. var reader = new StreamReader(ms);
  213. return reader.ReadToEnd();
  214. }
  215. }
  216. }
  217. /// <summary>
  218. /// Gets the optimized result using cache.
  219. /// </summary>
  220. /// <typeparam name="T"></typeparam>
  221. /// <param name="requestContext">The request context.</param>
  222. /// <param name="cacheKey">The cache key.</param>
  223. /// <param name="lastDateModified">The last date modified.</param>
  224. /// <param name="cacheDuration">Duration of the cache.</param>
  225. /// <param name="factoryFn">The factory fn.</param>
  226. /// <param name="responseHeaders">The response headers.</param>
  227. /// <returns>System.Object.</returns>
  228. /// <exception cref="System.ArgumentNullException">cacheKey
  229. /// or
  230. /// factoryFn</exception>
  231. public object GetOptimizedResultUsingCache<T>(IRequest requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, IDictionary<string, string> responseHeaders = null)
  232. where T : class
  233. {
  234. if (cacheKey == Guid.Empty)
  235. {
  236. throw new ArgumentNullException("cacheKey");
  237. }
  238. if (factoryFn == null)
  239. {
  240. throw new ArgumentNullException("factoryFn");
  241. }
  242. var key = cacheKey.ToString("N");
  243. if (responseHeaders == null)
  244. {
  245. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  246. }
  247. // See if the result is already cached in the browser
  248. var result = GetCachedResult(requestContext, responseHeaders, cacheKey, key, lastDateModified, cacheDuration, null);
  249. if (result != null)
  250. {
  251. return result;
  252. }
  253. return GetOptimizedResultInternal(requestContext, factoryFn(), false, responseHeaders);
  254. }
  255. /// <summary>
  256. /// To the cached result.
  257. /// </summary>
  258. /// <typeparam name="T"></typeparam>
  259. /// <param name="requestContext">The request context.</param>
  260. /// <param name="cacheKey">The cache key.</param>
  261. /// <param name="lastDateModified">The last date modified.</param>
  262. /// <param name="cacheDuration">Duration of the cache.</param>
  263. /// <param name="factoryFn">The factory fn.</param>
  264. /// <param name="contentType">Type of the content.</param>
  265. /// <param name="responseHeaders">The response headers.</param>
  266. /// <returns>System.Object.</returns>
  267. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  268. public object GetCachedResult<T>(IRequest requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, string contentType, IDictionary<string, string> responseHeaders = null)
  269. where T : class
  270. {
  271. if (cacheKey == Guid.Empty)
  272. {
  273. throw new ArgumentNullException("cacheKey");
  274. }
  275. if (factoryFn == null)
  276. {
  277. throw new ArgumentNullException("factoryFn");
  278. }
  279. var key = cacheKey.ToString("N");
  280. if (responseHeaders == null)
  281. {
  282. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  283. }
  284. // See if the result is already cached in the browser
  285. var result = GetCachedResult(requestContext, responseHeaders, cacheKey, key, lastDateModified, cacheDuration, contentType);
  286. if (result != null)
  287. {
  288. return result;
  289. }
  290. result = factoryFn();
  291. // Apply caching headers
  292. var hasHeaders = result as IHasHeaders;
  293. if (hasHeaders != null)
  294. {
  295. AddResponseHeaders(hasHeaders, responseHeaders);
  296. return hasHeaders;
  297. }
  298. return GetHttpResult(result, contentType, false, responseHeaders);
  299. }
  300. /// <summary>
  301. /// Pres the process optimized result.
  302. /// </summary>
  303. /// <param name="requestContext">The request context.</param>
  304. /// <param name="responseHeaders">The responseHeaders.</param>
  305. /// <param name="cacheKey">The cache key.</param>
  306. /// <param name="cacheKeyString">The cache key string.</param>
  307. /// <param name="lastDateModified">The last date modified.</param>
  308. /// <param name="cacheDuration">Duration of the cache.</param>
  309. /// <param name="contentType">Type of the content.</param>
  310. /// <returns>System.Object.</returns>
  311. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  312. {
  313. responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString);
  314. if (IsNotModified(requestContext, cacheKey, lastDateModified, cacheDuration))
  315. {
  316. AddAgeHeader(responseHeaders, lastDateModified);
  317. AddExpiresHeader(responseHeaders, cacheKeyString, cacheDuration);
  318. var result = new HttpResult(new byte[] { }, contentType ?? "text/html", HttpStatusCode.NotModified);
  319. AddResponseHeaders(result, responseHeaders);
  320. return result;
  321. }
  322. AddCachingHeaders(responseHeaders, cacheKeyString, lastDateModified, cacheDuration);
  323. return null;
  324. }
  325. public Task<object> GetStaticFileResult(IRequest requestContext,
  326. string path,
  327. FileShareMode fileShare = FileShareMode.Read)
  328. {
  329. if (string.IsNullOrEmpty(path))
  330. {
  331. throw new ArgumentNullException("path");
  332. }
  333. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  334. {
  335. Path = path,
  336. FileShare = fileShare
  337. });
  338. }
  339. public Task<object> GetStaticFileResult(IRequest requestContext,
  340. StaticFileResultOptions options)
  341. {
  342. var path = options.Path;
  343. var fileShare = options.FileShare;
  344. if (string.IsNullOrEmpty(path))
  345. {
  346. throw new ArgumentNullException("path");
  347. }
  348. if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
  349. {
  350. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  351. }
  352. if (string.IsNullOrWhiteSpace(options.ContentType))
  353. {
  354. options.ContentType = MimeTypes.GetMimeType(path);
  355. }
  356. if (!options.DateLastModified.HasValue)
  357. {
  358. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  359. }
  360. var cacheKey = path + options.DateLastModified.Value.Ticks;
  361. options.CacheKey = cacheKey.GetMD5();
  362. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  363. return GetStaticResult(requestContext, options);
  364. }
  365. /// <summary>
  366. /// Gets the file stream.
  367. /// </summary>
  368. /// <param name="path">The path.</param>
  369. /// <param name="fileShare">The file share.</param>
  370. /// <returns>Stream.</returns>
  371. private Stream GetFileStream(string path, FileShareMode fileShare)
  372. {
  373. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  374. }
  375. public Task<object> GetStaticResult(IRequest requestContext,
  376. Guid cacheKey,
  377. DateTime? lastDateModified,
  378. TimeSpan? cacheDuration,
  379. string contentType,
  380. Func<Task<Stream>> factoryFn,
  381. IDictionary<string, string> responseHeaders = null,
  382. bool isHeadRequest = false)
  383. {
  384. return GetStaticResult(requestContext, new StaticResultOptions
  385. {
  386. CacheDuration = cacheDuration,
  387. CacheKey = cacheKey,
  388. ContentFactory = factoryFn,
  389. ContentType = contentType,
  390. DateLastModified = lastDateModified,
  391. IsHeadRequest = isHeadRequest,
  392. ResponseHeaders = responseHeaders
  393. });
  394. }
  395. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  396. {
  397. var cacheKey = options.CacheKey;
  398. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  399. var contentType = options.ContentType;
  400. if (cacheKey == Guid.Empty)
  401. {
  402. throw new ArgumentNullException("cacheKey");
  403. }
  404. if (options.ContentFactory == null)
  405. {
  406. throw new ArgumentNullException("factoryFn");
  407. }
  408. var key = cacheKey.ToString("N");
  409. // See if the result is already cached in the browser
  410. var result = GetCachedResult(requestContext, options.ResponseHeaders, cacheKey, key, options.DateLastModified, options.CacheDuration, contentType);
  411. if (result != null)
  412. {
  413. return result;
  414. }
  415. var compress = ShouldCompressResponse(requestContext, contentType);
  416. var hasHeaders = await GetStaticResult(requestContext, options, compress).ConfigureAwait(false);
  417. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  418. return hasHeaders;
  419. }
  420. /// <summary>
  421. /// Shoulds the compress response.
  422. /// </summary>
  423. /// <param name="requestContext">The request context.</param>
  424. /// <param name="contentType">Type of the content.</param>
  425. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  426. private bool ShouldCompressResponse(IRequest requestContext, string contentType)
  427. {
  428. // It will take some work to support compression with byte range requests
  429. if (!string.IsNullOrEmpty(requestContext.Headers.Get("Range")))
  430. {
  431. return false;
  432. }
  433. // Don't compress media
  434. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  435. {
  436. return false;
  437. }
  438. // Don't compress images
  439. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  440. {
  441. return false;
  442. }
  443. if (contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  444. {
  445. return false;
  446. }
  447. if (contentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase))
  448. {
  449. if (string.Equals(contentType, "application/x-javascript", StringComparison.OrdinalIgnoreCase))
  450. {
  451. return true;
  452. }
  453. if (string.Equals(contentType, "application/xml", StringComparison.OrdinalIgnoreCase))
  454. {
  455. return true;
  456. }
  457. return false;
  458. }
  459. return true;
  460. }
  461. /// <summary>
  462. /// The us culture
  463. /// </summary>
  464. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  465. private async Task<IHasHeaders> GetStaticResult(IRequest requestContext, StaticResultOptions options, bool compress)
  466. {
  467. var isHeadRequest = options.IsHeadRequest;
  468. var factoryFn = options.ContentFactory;
  469. var contentType = options.ContentType;
  470. var responseHeaders = options.ResponseHeaders;
  471. var requestedCompressionType = GetCompressionType(requestContext);
  472. if (!compress || string.IsNullOrEmpty(requestedCompressionType))
  473. {
  474. var rangeHeader = requestContext.Headers.Get("Range");
  475. var stream = await factoryFn().ConfigureAwait(false);
  476. if (!string.IsNullOrEmpty(rangeHeader))
  477. {
  478. return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest, _logger)
  479. {
  480. OnComplete = options.OnComplete
  481. };
  482. }
  483. responseHeaders["Content-Length"] = stream.Length.ToString(UsCulture);
  484. if (isHeadRequest)
  485. {
  486. stream.Dispose();
  487. return GetHttpResult(new byte[] { }, contentType, true);
  488. }
  489. return new StreamWriter(stream, contentType, _logger)
  490. {
  491. OnComplete = options.OnComplete,
  492. OnError = options.OnError
  493. };
  494. }
  495. using (var stream = await factoryFn().ConfigureAwait(false))
  496. {
  497. return await GetCompressedResult(stream, requestedCompressionType, responseHeaders, isHeadRequest, contentType).ConfigureAwait(false);
  498. }
  499. }
  500. private async Task<IHasHeaders> GetCompressedResult(Stream stream,
  501. string requestedCompressionType,
  502. IDictionary<string,string> responseHeaders,
  503. bool isHeadRequest,
  504. string contentType)
  505. {
  506. using (var reader = new MemoryStream())
  507. {
  508. await stream.CopyToAsync(reader).ConfigureAwait(false);
  509. reader.Position = 0;
  510. var content = reader.ToArray();
  511. if (content.Length >= 1024)
  512. {
  513. content = Compress(content, requestedCompressionType);
  514. responseHeaders["Content-Encoding"] = requestedCompressionType;
  515. }
  516. responseHeaders["Content-Length"] = content.Length.ToString(UsCulture);
  517. if (isHeadRequest)
  518. {
  519. return GetHttpResult(new byte[] { }, contentType, true);
  520. }
  521. return GetHttpResult(content, contentType, true, responseHeaders);
  522. }
  523. }
  524. private byte[] Compress(byte[] bytes, string compressionType)
  525. {
  526. if (compressionType == "deflate")
  527. return Deflate(bytes);
  528. if (compressionType == "gzip")
  529. return GZip(bytes);
  530. throw new NotSupportedException(compressionType);
  531. }
  532. private byte[] Deflate(byte[] bytes)
  533. {
  534. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  535. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  536. using (var ms = new MemoryStream())
  537. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  538. {
  539. zipStream.Write(bytes, 0, bytes.Length);
  540. zipStream.Dispose();
  541. return ms.ToArray();
  542. }
  543. }
  544. private byte[] GZip(byte[] buffer)
  545. {
  546. using (var ms = new MemoryStream())
  547. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  548. {
  549. zipStream.Write(buffer, 0, buffer.Length);
  550. zipStream.Dispose();
  551. return ms.ToArray();
  552. }
  553. }
  554. /// <summary>
  555. /// Adds the caching responseHeaders.
  556. /// </summary>
  557. /// <param name="responseHeaders">The responseHeaders.</param>
  558. /// <param name="cacheKey">The cache key.</param>
  559. /// <param name="lastDateModified">The last date modified.</param>
  560. /// <param name="cacheDuration">Duration of the cache.</param>
  561. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  562. {
  563. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  564. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  565. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  566. {
  567. AddAgeHeader(responseHeaders, lastDateModified);
  568. responseHeaders["Last-Modified"] = lastDateModified.Value.ToString("r");
  569. }
  570. if (cacheDuration.HasValue)
  571. {
  572. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  573. }
  574. else if (!string.IsNullOrEmpty(cacheKey))
  575. {
  576. responseHeaders["Cache-Control"] = "public";
  577. }
  578. else
  579. {
  580. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  581. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  582. }
  583. AddExpiresHeader(responseHeaders, cacheKey, cacheDuration);
  584. }
  585. /// <summary>
  586. /// Adds the expires header.
  587. /// </summary>
  588. /// <param name="responseHeaders">The responseHeaders.</param>
  589. /// <param name="cacheKey">The cache key.</param>
  590. /// <param name="cacheDuration">Duration of the cache.</param>
  591. private void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration)
  592. {
  593. if (cacheDuration.HasValue)
  594. {
  595. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  596. }
  597. else if (string.IsNullOrEmpty(cacheKey))
  598. {
  599. responseHeaders["Expires"] = "-1";
  600. }
  601. }
  602. /// <summary>
  603. /// Adds the age header.
  604. /// </summary>
  605. /// <param name="responseHeaders">The responseHeaders.</param>
  606. /// <param name="lastDateModified">The last date modified.</param>
  607. private void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  608. {
  609. if (lastDateModified.HasValue)
  610. {
  611. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  612. }
  613. }
  614. /// <summary>
  615. /// Determines whether [is not modified] [the specified cache key].
  616. /// </summary>
  617. /// <param name="requestContext">The request context.</param>
  618. /// <param name="cacheKey">The cache key.</param>
  619. /// <param name="lastDateModified">The last date modified.</param>
  620. /// <param name="cacheDuration">Duration of the cache.</param>
  621. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  622. private bool IsNotModified(IRequest requestContext, Guid? cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  623. {
  624. //var isNotModified = true;
  625. var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since");
  626. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  627. {
  628. DateTime ifModifiedSince;
  629. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  630. {
  631. if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  632. {
  633. return true;
  634. }
  635. }
  636. }
  637. var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match");
  638. // Validate If-None-Match
  639. if ((cacheKey.HasValue || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  640. {
  641. Guid ifNoneMatch;
  642. ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"');
  643. if (Guid.TryParse(ifNoneMatchHeader, out ifNoneMatch))
  644. {
  645. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  646. {
  647. return true;
  648. }
  649. }
  650. }
  651. return false;
  652. }
  653. /// <summary>
  654. /// Determines whether [is not modified] [the specified if modified since].
  655. /// </summary>
  656. /// <param name="ifModifiedSince">If modified since.</param>
  657. /// <param name="cacheDuration">Duration of the cache.</param>
  658. /// <param name="dateModified">The date modified.</param>
  659. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  660. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  661. {
  662. if (dateModified.HasValue)
  663. {
  664. var lastModified = NormalizeDateForComparison(dateModified.Value);
  665. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  666. return lastModified <= ifModifiedSince;
  667. }
  668. if (cacheDuration.HasValue)
  669. {
  670. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  671. if (DateTime.UtcNow < cacheExpirationDate)
  672. {
  673. return true;
  674. }
  675. }
  676. return false;
  677. }
  678. /// <summary>
  679. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  680. /// </summary>
  681. /// <param name="date">The date.</param>
  682. /// <returns>DateTime.</returns>
  683. private DateTime NormalizeDateForComparison(DateTime date)
  684. {
  685. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  686. }
  687. /// <summary>
  688. /// Adds the response headers.
  689. /// </summary>
  690. /// <param name="hasHeaders">The has options.</param>
  691. /// <param name="responseHeaders">The response headers.</param>
  692. private void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  693. {
  694. foreach (var item in responseHeaders)
  695. {
  696. hasHeaders.Headers[item.Key] = item.Value;
  697. }
  698. }
  699. }
  700. }