HttpResultFactory.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  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. if (addCachePrevention)
  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. using (var compressionStream = GetCompressionStream(ms, compressionType))
  178. {
  179. ContentTypes.Instance.SerializeToStream(request, dto, compressionStream);
  180. compressionStream.Dispose();
  181. var compressedBytes = ms.ToArray();
  182. var httpResult = new StreamWriter(compressedBytes, request.ResponseContentType, _logger);
  183. //httpResult.Headers["Content-Length"] = compressedBytes.Length.ToString(UsCulture);
  184. httpResult.Headers["Content-Encoding"] = compressionType;
  185. return httpResult;
  186. }
  187. }
  188. }
  189. private static Stream GetCompressionStream(Stream outputStream, string compressionType)
  190. {
  191. if (compressionType == "deflate")
  192. return new DeflateStream(outputStream, CompressionMode.Compress, true);
  193. if (compressionType == "gzip")
  194. return new GZipStream(outputStream, CompressionMode.Compress, true);
  195. throw new NotSupportedException(compressionType);
  196. }
  197. public static string GetRealContentType(string contentType)
  198. {
  199. return contentType == null
  200. ? null
  201. : contentType.Split(';')[0].ToLower().Trim();
  202. }
  203. private string SerializeToXmlString(object from)
  204. {
  205. using (var ms = new MemoryStream())
  206. {
  207. var xwSettings = new XmlWriterSettings();
  208. xwSettings.Encoding = new UTF8Encoding(false);
  209. xwSettings.OmitXmlDeclaration = false;
  210. using (var xw = XmlWriter.Create(ms, xwSettings))
  211. {
  212. var serializer = new DataContractSerializer(from.GetType());
  213. serializer.WriteObject(xw, from);
  214. xw.Flush();
  215. ms.Seek(0, SeekOrigin.Begin);
  216. var reader = new StreamReader(ms);
  217. return reader.ReadToEnd();
  218. }
  219. }
  220. }
  221. /// <summary>
  222. /// Gets the optimized result using cache.
  223. /// </summary>
  224. /// <typeparam name="T"></typeparam>
  225. /// <param name="requestContext">The request context.</param>
  226. /// <param name="cacheKey">The cache key.</param>
  227. /// <param name="lastDateModified">The last date modified.</param>
  228. /// <param name="cacheDuration">Duration of the cache.</param>
  229. /// <param name="factoryFn">The factory fn.</param>
  230. /// <param name="responseHeaders">The response headers.</param>
  231. /// <returns>System.Object.</returns>
  232. /// <exception cref="System.ArgumentNullException">cacheKey
  233. /// or
  234. /// factoryFn</exception>
  235. public object GetOptimizedResultUsingCache<T>(IRequest requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, IDictionary<string, string> responseHeaders = null)
  236. where T : class
  237. {
  238. if (cacheKey == Guid.Empty)
  239. {
  240. throw new ArgumentNullException("cacheKey");
  241. }
  242. if (factoryFn == null)
  243. {
  244. throw new ArgumentNullException("factoryFn");
  245. }
  246. var key = cacheKey.ToString("N");
  247. if (responseHeaders == null)
  248. {
  249. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  250. }
  251. // See if the result is already cached in the browser
  252. var result = GetCachedResult(requestContext, responseHeaders, cacheKey, key, lastDateModified, cacheDuration, null);
  253. if (result != null)
  254. {
  255. return result;
  256. }
  257. return GetOptimizedResultInternal(requestContext, factoryFn(), false, responseHeaders);
  258. }
  259. /// <summary>
  260. /// To the cached result.
  261. /// </summary>
  262. /// <typeparam name="T"></typeparam>
  263. /// <param name="requestContext">The request context.</param>
  264. /// <param name="cacheKey">The cache key.</param>
  265. /// <param name="lastDateModified">The last date modified.</param>
  266. /// <param name="cacheDuration">Duration of the cache.</param>
  267. /// <param name="factoryFn">The factory fn.</param>
  268. /// <param name="contentType">Type of the content.</param>
  269. /// <param name="responseHeaders">The response headers.</param>
  270. /// <returns>System.Object.</returns>
  271. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  272. public object GetCachedResult<T>(IRequest requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, string contentType, IDictionary<string, string> responseHeaders = null)
  273. where T : class
  274. {
  275. if (cacheKey == Guid.Empty)
  276. {
  277. throw new ArgumentNullException("cacheKey");
  278. }
  279. if (factoryFn == null)
  280. {
  281. throw new ArgumentNullException("factoryFn");
  282. }
  283. var key = cacheKey.ToString("N");
  284. if (responseHeaders == null)
  285. {
  286. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  287. }
  288. // See if the result is already cached in the browser
  289. var result = GetCachedResult(requestContext, responseHeaders, cacheKey, key, lastDateModified, cacheDuration, contentType);
  290. if (result != null)
  291. {
  292. return result;
  293. }
  294. result = factoryFn();
  295. // Apply caching headers
  296. var hasHeaders = result as IHasHeaders;
  297. if (hasHeaders != null)
  298. {
  299. AddResponseHeaders(hasHeaders, responseHeaders);
  300. return hasHeaders;
  301. }
  302. return GetHttpResult(result, contentType, false, responseHeaders);
  303. }
  304. /// <summary>
  305. /// Pres the process optimized result.
  306. /// </summary>
  307. /// <param name="requestContext">The request context.</param>
  308. /// <param name="responseHeaders">The responseHeaders.</param>
  309. /// <param name="cacheKey">The cache key.</param>
  310. /// <param name="cacheKeyString">The cache key string.</param>
  311. /// <param name="lastDateModified">The last date modified.</param>
  312. /// <param name="cacheDuration">Duration of the cache.</param>
  313. /// <param name="contentType">Type of the content.</param>
  314. /// <returns>System.Object.</returns>
  315. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  316. {
  317. responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString);
  318. if (IsNotModified(requestContext, cacheKey, lastDateModified, cacheDuration))
  319. {
  320. AddAgeHeader(responseHeaders, lastDateModified);
  321. AddExpiresHeader(responseHeaders, cacheKeyString, cacheDuration);
  322. var result = new HttpResult(new byte[] { }, contentType ?? "text/html", HttpStatusCode.NotModified);
  323. AddResponseHeaders(result, responseHeaders);
  324. return result;
  325. }
  326. AddCachingHeaders(responseHeaders, cacheKeyString, lastDateModified, cacheDuration);
  327. return null;
  328. }
  329. public Task<object> GetStaticFileResult(IRequest requestContext,
  330. string path,
  331. FileShareMode fileShare = FileShareMode.Read)
  332. {
  333. if (string.IsNullOrEmpty(path))
  334. {
  335. throw new ArgumentNullException("path");
  336. }
  337. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  338. {
  339. Path = path,
  340. FileShare = fileShare
  341. });
  342. }
  343. public Task<object> GetStaticFileResult(IRequest requestContext,
  344. StaticFileResultOptions options)
  345. {
  346. var path = options.Path;
  347. var fileShare = options.FileShare;
  348. if (string.IsNullOrEmpty(path))
  349. {
  350. throw new ArgumentNullException("path");
  351. }
  352. if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
  353. {
  354. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  355. }
  356. if (string.IsNullOrWhiteSpace(options.ContentType))
  357. {
  358. options.ContentType = MimeTypes.GetMimeType(path);
  359. }
  360. if (!options.DateLastModified.HasValue)
  361. {
  362. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  363. }
  364. var cacheKey = path + options.DateLastModified.Value.Ticks;
  365. options.CacheKey = cacheKey.GetMD5();
  366. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  367. return GetStaticResult(requestContext, options);
  368. }
  369. /// <summary>
  370. /// Gets the file stream.
  371. /// </summary>
  372. /// <param name="path">The path.</param>
  373. /// <param name="fileShare">The file share.</param>
  374. /// <returns>Stream.</returns>
  375. private Stream GetFileStream(string path, FileShareMode fileShare)
  376. {
  377. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  378. }
  379. public Task<object> GetStaticResult(IRequest requestContext,
  380. Guid cacheKey,
  381. DateTime? lastDateModified,
  382. TimeSpan? cacheDuration,
  383. string contentType,
  384. Func<Task<Stream>> factoryFn,
  385. IDictionary<string, string> responseHeaders = null,
  386. bool isHeadRequest = false)
  387. {
  388. return GetStaticResult(requestContext, new StaticResultOptions
  389. {
  390. CacheDuration = cacheDuration,
  391. CacheKey = cacheKey,
  392. ContentFactory = factoryFn,
  393. ContentType = contentType,
  394. DateLastModified = lastDateModified,
  395. IsHeadRequest = isHeadRequest,
  396. ResponseHeaders = responseHeaders
  397. });
  398. }
  399. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  400. {
  401. var cacheKey = options.CacheKey;
  402. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  403. var contentType = options.ContentType;
  404. if (cacheKey == Guid.Empty)
  405. {
  406. throw new ArgumentNullException("cacheKey");
  407. }
  408. if (options.ContentFactory == null)
  409. {
  410. throw new ArgumentNullException("factoryFn");
  411. }
  412. var key = cacheKey.ToString("N");
  413. // See if the result is already cached in the browser
  414. var result = GetCachedResult(requestContext, options.ResponseHeaders, cacheKey, key, options.DateLastModified, options.CacheDuration, contentType);
  415. if (result != null)
  416. {
  417. return result;
  418. }
  419. var compress = ShouldCompressResponse(requestContext, contentType);
  420. var hasHeaders = await GetStaticResult(requestContext, options, compress).ConfigureAwait(false);
  421. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  422. return hasHeaders;
  423. }
  424. /// <summary>
  425. /// Shoulds the compress response.
  426. /// </summary>
  427. /// <param name="requestContext">The request context.</param>
  428. /// <param name="contentType">Type of the content.</param>
  429. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  430. private bool ShouldCompressResponse(IRequest requestContext, string contentType)
  431. {
  432. // It will take some work to support compression with byte range requests
  433. if (!string.IsNullOrEmpty(requestContext.Headers.Get("Range")))
  434. {
  435. return false;
  436. }
  437. // Don't compress media
  438. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  439. {
  440. return false;
  441. }
  442. // Don't compress images
  443. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  444. {
  445. return false;
  446. }
  447. if (contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  448. {
  449. return false;
  450. }
  451. if (contentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase))
  452. {
  453. if (string.Equals(contentType, "application/x-javascript", StringComparison.OrdinalIgnoreCase))
  454. {
  455. return true;
  456. }
  457. if (string.Equals(contentType, "application/xml", StringComparison.OrdinalIgnoreCase))
  458. {
  459. return true;
  460. }
  461. return false;
  462. }
  463. return true;
  464. }
  465. /// <summary>
  466. /// The us culture
  467. /// </summary>
  468. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  469. private async Task<IHasHeaders> GetStaticResult(IRequest requestContext, StaticResultOptions options, bool compress)
  470. {
  471. var isHeadRequest = options.IsHeadRequest;
  472. var factoryFn = options.ContentFactory;
  473. var contentType = options.ContentType;
  474. var responseHeaders = options.ResponseHeaders;
  475. var requestedCompressionType = GetCompressionType(requestContext);
  476. if (!compress || string.IsNullOrEmpty(requestedCompressionType))
  477. {
  478. var rangeHeader = requestContext.Headers.Get("Range");
  479. var stream = await factoryFn().ConfigureAwait(false);
  480. if (!string.IsNullOrEmpty(rangeHeader))
  481. {
  482. return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest, _logger)
  483. {
  484. OnComplete = options.OnComplete
  485. };
  486. }
  487. responseHeaders["Content-Length"] = stream.Length.ToString(UsCulture);
  488. if (isHeadRequest)
  489. {
  490. stream.Dispose();
  491. return GetHttpResult(new byte[] { }, contentType, true);
  492. }
  493. return new StreamWriter(stream, contentType, _logger)
  494. {
  495. OnComplete = options.OnComplete,
  496. OnError = options.OnError
  497. };
  498. }
  499. string content;
  500. using (var stream = await factoryFn().ConfigureAwait(false))
  501. {
  502. using (var reader = new StreamReader(stream))
  503. {
  504. content = await reader.ReadToEndAsync().ConfigureAwait(false);
  505. }
  506. }
  507. var contents = Compress(content, requestedCompressionType);
  508. responseHeaders["Content-Length"] = contents.Length.ToString(UsCulture);
  509. responseHeaders["Content-Encoding"] = requestedCompressionType;
  510. if (isHeadRequest)
  511. {
  512. return GetHttpResult(new byte[] { }, contentType, true);
  513. }
  514. return GetHttpResult(contents, contentType, true, responseHeaders);
  515. }
  516. private byte[] Compress(string text, string compressionType)
  517. {
  518. if (compressionType == "deflate")
  519. return Deflate(text);
  520. if (compressionType == "gzip")
  521. return GZip(text);
  522. throw new NotSupportedException(compressionType);
  523. }
  524. private byte[] Deflate(string text)
  525. {
  526. return Deflate(Encoding.UTF8.GetBytes(text));
  527. }
  528. private byte[] Deflate(byte[] bytes)
  529. {
  530. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  531. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  532. using (var ms = new MemoryStream())
  533. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  534. {
  535. zipStream.Write(bytes, 0, bytes.Length);
  536. zipStream.Dispose();
  537. return ms.ToArray();
  538. }
  539. }
  540. private byte[] GZip(string text)
  541. {
  542. return GZip(Encoding.UTF8.GetBytes(text));
  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. isNotModified = IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified);
  632. }
  633. }
  634. var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match");
  635. // Validate If-None-Match
  636. if (isNotModified && (cacheKey.HasValue || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  637. {
  638. Guid ifNoneMatch;
  639. if (Guid.TryParse(ifNoneMatchHeader ?? string.Empty, out ifNoneMatch))
  640. {
  641. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  642. {
  643. return true;
  644. }
  645. }
  646. }
  647. return false;
  648. }
  649. /// <summary>
  650. /// Determines whether [is not modified] [the specified if modified since].
  651. /// </summary>
  652. /// <param name="ifModifiedSince">If modified since.</param>
  653. /// <param name="cacheDuration">Duration of the cache.</param>
  654. /// <param name="dateModified">The date modified.</param>
  655. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  656. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  657. {
  658. if (dateModified.HasValue)
  659. {
  660. var lastModified = NormalizeDateForComparison(dateModified.Value);
  661. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  662. return lastModified <= ifModifiedSince;
  663. }
  664. if (cacheDuration.HasValue)
  665. {
  666. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  667. if (DateTime.UtcNow < cacheExpirationDate)
  668. {
  669. return true;
  670. }
  671. }
  672. return false;
  673. }
  674. /// <summary>
  675. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  676. /// </summary>
  677. /// <param name="date">The date.</param>
  678. /// <returns>DateTime.</returns>
  679. private DateTime NormalizeDateForComparison(DateTime date)
  680. {
  681. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  682. }
  683. /// <summary>
  684. /// Adds the response headers.
  685. /// </summary>
  686. /// <param name="hasHeaders">The has options.</param>
  687. /// <param name="responseHeaders">The response headers.</param>
  688. private void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  689. {
  690. foreach (var item in responseHeaders)
  691. {
  692. hasHeaders.Headers[item.Key] = item.Value;
  693. }
  694. }
  695. }
  696. }