HttpResultFactory.cs 31 KB

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