HttpResultFactory.cs 31 KB

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