HttpResultFactory.cs 31 KB

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