HttpResultFactory.cs 31 KB

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