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 IRequest = MediaBrowser.Model.Services.IRequest;
  20. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  21. using StreamWriter = Emby.Server.Implementations.HttpServer.StreamWriter;
  22. namespace Emby.Server.Implementations.HttpServer
  23. {
  24. /// <summary>
  25. /// Class HttpResultFactory
  26. /// </summary>
  27. public class HttpResultFactory : IHttpResultFactory
  28. {
  29. /// <summary>
  30. /// The _logger
  31. /// </summary>
  32. private readonly ILogger _logger;
  33. private readonly IFileSystem _fileSystem;
  34. private readonly IJsonSerializer _jsonSerializer;
  35. private readonly IMemoryStreamFactory _memoryStreamFactory;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
  38. /// </summary>
  39. public HttpResultFactory(ILogManager logManager, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IMemoryStreamFactory memoryStreamFactory)
  40. {
  41. _fileSystem = fileSystem;
  42. _jsonSerializer = jsonSerializer;
  43. _memoryStreamFactory = memoryStreamFactory;
  44. _logger = logManager.GetLogger("HttpResultFactory");
  45. }
  46. /// <summary>
  47. /// Gets the result.
  48. /// </summary>
  49. /// <param name="content">The content.</param>
  50. /// <param name="contentType">Type of the content.</param>
  51. /// <param name="responseHeaders">The response headers.</param>
  52. /// <returns>System.Object.</returns>
  53. public object GetResult(object content, string contentType, IDictionary<string, string> responseHeaders = null)
  54. {
  55. return GetHttpResult(content, contentType, true, responseHeaders);
  56. }
  57. /// <summary>
  58. /// Gets the HTTP result.
  59. /// </summary>
  60. private IHasHeaders GetHttpResult(object content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  61. {
  62. IHasHeaders result;
  63. var stream = content as Stream;
  64. if (stream != null)
  65. {
  66. result = new StreamWriter(stream, contentType, _logger);
  67. }
  68. else
  69. {
  70. var bytes = content as byte[];
  71. if (bytes != null)
  72. {
  73. result = new StreamWriter(bytes, contentType, _logger);
  74. }
  75. else
  76. {
  77. var text = content as string;
  78. if (text != null)
  79. {
  80. result = new StreamWriter(Encoding.UTF8.GetBytes(text), contentType, _logger);
  81. }
  82. else
  83. {
  84. result = new HttpResult(content, contentType, HttpStatusCode.OK);
  85. }
  86. }
  87. }
  88. if (responseHeaders == null)
  89. {
  90. responseHeaders = new Dictionary<string, string>();
  91. }
  92. string expires;
  93. if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out expires))
  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. var contentType = request.ResponseContentType;
  178. var writerFn = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
  179. writerFn(dto, ms);
  180. ms.Position = 0;
  181. var responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  182. return GetCompressedResult(ms, compressionType, responseHeaders, false, request.ResponseContentType).Result;
  183. }
  184. }
  185. private static Stream GetCompressionStream(Stream outputStream, string compressionType)
  186. {
  187. if (compressionType == "deflate")
  188. return new DeflateStream(outputStream, CompressionMode.Compress, true);
  189. if (compressionType == "gzip")
  190. return new GZipStream(outputStream, CompressionMode.Compress, true);
  191. throw new NotSupportedException(compressionType);
  192. }
  193. public static string GetRealContentType(string contentType)
  194. {
  195. return contentType == null
  196. ? null
  197. : contentType.Split(';')[0].ToLower().Trim();
  198. }
  199. private string SerializeToXmlString(object from)
  200. {
  201. using (var ms = new MemoryStream())
  202. {
  203. var xwSettings = new XmlWriterSettings();
  204. xwSettings.Encoding = new UTF8Encoding(false);
  205. xwSettings.OmitXmlDeclaration = false;
  206. using (var xw = XmlWriter.Create(ms, xwSettings))
  207. {
  208. var serializer = new DataContractSerializer(from.GetType());
  209. serializer.WriteObject(xw, from);
  210. xw.Flush();
  211. ms.Seek(0, SeekOrigin.Begin);
  212. var reader = new StreamReader(ms);
  213. return reader.ReadToEnd();
  214. }
  215. }
  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. return GetHttpResult(result, contentType, false, responseHeaders);
  299. }
  300. /// <summary>
  301. /// Pres the process optimized result.
  302. /// </summary>
  303. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  304. {
  305. responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString);
  306. var noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
  307. if (!noCache)
  308. {
  309. if (IsNotModified(requestContext, cacheKey, lastDateModified, cacheDuration))
  310. {
  311. AddAgeHeader(responseHeaders, lastDateModified);
  312. AddExpiresHeader(responseHeaders, cacheKeyString, cacheDuration, noCache);
  313. var result = new HttpResult(new byte[] { }, contentType ?? "text/html", HttpStatusCode.NotModified);
  314. AddResponseHeaders(result, responseHeaders);
  315. return result;
  316. }
  317. }
  318. AddCachingHeaders(responseHeaders, cacheKeyString, lastDateModified, cacheDuration, noCache);
  319. return null;
  320. }
  321. public Task<object> GetStaticFileResult(IRequest requestContext,
  322. string path,
  323. FileShareMode fileShare = FileShareMode.Read)
  324. {
  325. if (string.IsNullOrEmpty(path))
  326. {
  327. throw new ArgumentNullException("path");
  328. }
  329. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  330. {
  331. Path = path,
  332. FileShare = fileShare
  333. });
  334. }
  335. public Task<object> GetStaticFileResult(IRequest requestContext,
  336. StaticFileResultOptions options)
  337. {
  338. var path = options.Path;
  339. var fileShare = options.FileShare;
  340. if (string.IsNullOrEmpty(path))
  341. {
  342. throw new ArgumentNullException("path");
  343. }
  344. if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
  345. {
  346. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  347. }
  348. if (string.IsNullOrWhiteSpace(options.ContentType))
  349. {
  350. options.ContentType = MimeTypes.GetMimeType(path);
  351. }
  352. if (!options.DateLastModified.HasValue)
  353. {
  354. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  355. }
  356. var cacheKey = path + options.DateLastModified.Value.Ticks;
  357. options.CacheKey = cacheKey.GetMD5();
  358. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  359. return GetStaticResult(requestContext, options);
  360. }
  361. /// <summary>
  362. /// Gets the file stream.
  363. /// </summary>
  364. /// <param name="path">The path.</param>
  365. /// <param name="fileShare">The file share.</param>
  366. /// <returns>Stream.</returns>
  367. private Stream GetFileStream(string path, FileShareMode fileShare)
  368. {
  369. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  370. }
  371. public Task<object> GetStaticResult(IRequest requestContext,
  372. Guid cacheKey,
  373. DateTime? lastDateModified,
  374. TimeSpan? cacheDuration,
  375. string contentType,
  376. Func<Task<Stream>> factoryFn,
  377. IDictionary<string, string> responseHeaders = null,
  378. bool isHeadRequest = false)
  379. {
  380. return GetStaticResult(requestContext, new StaticResultOptions
  381. {
  382. CacheDuration = cacheDuration,
  383. CacheKey = cacheKey,
  384. ContentFactory = factoryFn,
  385. ContentType = contentType,
  386. DateLastModified = lastDateModified,
  387. IsHeadRequest = isHeadRequest,
  388. ResponseHeaders = responseHeaders
  389. });
  390. }
  391. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  392. {
  393. var cacheKey = options.CacheKey;
  394. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  395. var contentType = options.ContentType;
  396. if (cacheKey == Guid.Empty)
  397. {
  398. throw new ArgumentNullException("cacheKey");
  399. }
  400. var key = cacheKey.ToString("N");
  401. // See if the result is already cached in the browser
  402. var result = GetCachedResult(requestContext, options.ResponseHeaders, cacheKey, key, options.DateLastModified, options.CacheDuration, contentType);
  403. if (result != null)
  404. {
  405. return result;
  406. }
  407. var compress = ShouldCompressResponse(requestContext, contentType);
  408. var hasHeaders = await GetStaticResult(requestContext, options, compress).ConfigureAwait(false);
  409. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  410. return hasHeaders;
  411. }
  412. /// <summary>
  413. /// Shoulds the compress response.
  414. /// </summary>
  415. /// <param name="requestContext">The request context.</param>
  416. /// <param name="contentType">Type of the content.</param>
  417. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  418. private bool ShouldCompressResponse(IRequest requestContext, string contentType)
  419. {
  420. // It will take some work to support compression with byte range requests
  421. if (!string.IsNullOrWhiteSpace(requestContext.Headers.Get("Range")))
  422. {
  423. return false;
  424. }
  425. // Don't compress media
  426. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  427. {
  428. return false;
  429. }
  430. // Don't compress images
  431. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  432. {
  433. return false;
  434. }
  435. if (contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  436. {
  437. return false;
  438. }
  439. if (contentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase))
  440. {
  441. if (string.Equals(contentType, "application/x-javascript", StringComparison.OrdinalIgnoreCase))
  442. {
  443. return true;
  444. }
  445. if (string.Equals(contentType, "application/xml", StringComparison.OrdinalIgnoreCase))
  446. {
  447. return true;
  448. }
  449. return false;
  450. }
  451. return true;
  452. }
  453. /// <summary>
  454. /// The us culture
  455. /// </summary>
  456. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  457. private async Task<IHasHeaders> GetStaticResult(IRequest requestContext, StaticResultOptions options, bool compress)
  458. {
  459. var isHeadRequest = options.IsHeadRequest;
  460. var factoryFn = options.ContentFactory;
  461. var contentType = options.ContentType;
  462. var responseHeaders = options.ResponseHeaders;
  463. var requestedCompressionType = GetCompressionType(requestContext);
  464. if (!compress || string.IsNullOrEmpty(requestedCompressionType))
  465. {
  466. var rangeHeader = requestContext.Headers.Get("Range");
  467. if (!isHeadRequest && !string.IsNullOrWhiteSpace(options.Path))
  468. {
  469. return new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
  470. {
  471. OnComplete = options.OnComplete,
  472. OnError = options.OnError,
  473. FileShare = options.FileShare
  474. };
  475. }
  476. if (!string.IsNullOrWhiteSpace(rangeHeader))
  477. {
  478. var stream = await factoryFn().ConfigureAwait(false);
  479. return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest, _logger)
  480. {
  481. OnComplete = options.OnComplete
  482. };
  483. }
  484. else
  485. {
  486. var stream = await factoryFn().ConfigureAwait(false);
  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. }
  500. using (var stream = await factoryFn().ConfigureAwait(false))
  501. {
  502. return await GetCompressedResult(stream, requestedCompressionType, responseHeaders, isHeadRequest, contentType).ConfigureAwait(false);
  503. }
  504. }
  505. private async Task<IHasHeaders> GetCompressedResult(Stream stream,
  506. string requestedCompressionType,
  507. IDictionary<string,string> responseHeaders,
  508. bool isHeadRequest,
  509. string contentType)
  510. {
  511. using (var reader = new MemoryStream())
  512. {
  513. await stream.CopyToAsync(reader).ConfigureAwait(false);
  514. reader.Position = 0;
  515. var content = reader.ToArray();
  516. if (content.Length >= 1024)
  517. {
  518. content = Compress(content, requestedCompressionType);
  519. responseHeaders["Content-Encoding"] = requestedCompressionType;
  520. }
  521. responseHeaders["Vary"] = "Accept-Encoding";
  522. responseHeaders["Content-Length"] = content.Length.ToString(UsCulture);
  523. if (isHeadRequest)
  524. {
  525. return GetHttpResult(new byte[] { }, contentType, true);
  526. }
  527. return GetHttpResult(content, contentType, true, responseHeaders);
  528. }
  529. }
  530. private byte[] Compress(byte[] bytes, string compressionType)
  531. {
  532. if (compressionType == "deflate")
  533. return Deflate(bytes);
  534. if (compressionType == "gzip")
  535. return GZip(bytes);
  536. throw new NotSupportedException(compressionType);
  537. }
  538. private byte[] Deflate(byte[] bytes)
  539. {
  540. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  541. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  542. using (var ms = new MemoryStream())
  543. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  544. {
  545. zipStream.Write(bytes, 0, bytes.Length);
  546. zipStream.Dispose();
  547. return ms.ToArray();
  548. }
  549. }
  550. private byte[] GZip(byte[] buffer)
  551. {
  552. using (var ms = new MemoryStream())
  553. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  554. {
  555. zipStream.Write(buffer, 0, buffer.Length);
  556. zipStream.Dispose();
  557. return ms.ToArray();
  558. }
  559. }
  560. /// <summary>
  561. /// Adds the caching responseHeaders.
  562. /// </summary>
  563. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, bool noCache)
  564. {
  565. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  566. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  567. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  568. {
  569. AddAgeHeader(responseHeaders, lastDateModified);
  570. responseHeaders["Last-Modified"] = lastDateModified.Value.ToString("r");
  571. }
  572. if (!noCache && cacheDuration.HasValue)
  573. {
  574. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  575. }
  576. else if (!noCache && !string.IsNullOrEmpty(cacheKey))
  577. {
  578. responseHeaders["Cache-Control"] = "public";
  579. }
  580. else
  581. {
  582. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  583. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  584. }
  585. AddExpiresHeader(responseHeaders, cacheKey, cacheDuration, noCache);
  586. }
  587. /// <summary>
  588. /// Adds the expires header.
  589. /// </summary>
  590. private void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration, bool noCache)
  591. {
  592. if (!noCache && cacheDuration.HasValue)
  593. {
  594. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  595. }
  596. else if (string.IsNullOrEmpty(cacheKey))
  597. {
  598. responseHeaders["Expires"] = "-1";
  599. }
  600. }
  601. /// <summary>
  602. /// Adds the age header.
  603. /// </summary>
  604. /// <param name="responseHeaders">The responseHeaders.</param>
  605. /// <param name="lastDateModified">The last date modified.</param>
  606. private void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  607. {
  608. if (lastDateModified.HasValue)
  609. {
  610. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  611. }
  612. }
  613. /// <summary>
  614. /// Determines whether [is not modified] [the specified cache key].
  615. /// </summary>
  616. /// <param name="requestContext">The request context.</param>
  617. /// <param name="cacheKey">The cache key.</param>
  618. /// <param name="lastDateModified">The last date modified.</param>
  619. /// <param name="cacheDuration">Duration of the cache.</param>
  620. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  621. private bool IsNotModified(IRequest requestContext, Guid? cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  622. {
  623. //var isNotModified = true;
  624. var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since");
  625. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  626. {
  627. DateTime ifModifiedSince;
  628. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  629. {
  630. if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  631. {
  632. return true;
  633. }
  634. }
  635. }
  636. var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match");
  637. // Validate If-None-Match
  638. if ((cacheKey.HasValue || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  639. {
  640. Guid ifNoneMatch;
  641. ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"');
  642. if (Guid.TryParse(ifNoneMatchHeader, out ifNoneMatch))
  643. {
  644. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  645. {
  646. return true;
  647. }
  648. }
  649. }
  650. return false;
  651. }
  652. /// <summary>
  653. /// Determines whether [is not modified] [the specified if modified since].
  654. /// </summary>
  655. /// <param name="ifModifiedSince">If modified since.</param>
  656. /// <param name="cacheDuration">Duration of the cache.</param>
  657. /// <param name="dateModified">The date modified.</param>
  658. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  659. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  660. {
  661. if (dateModified.HasValue)
  662. {
  663. var lastModified = NormalizeDateForComparison(dateModified.Value);
  664. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  665. return lastModified <= ifModifiedSince;
  666. }
  667. if (cacheDuration.HasValue)
  668. {
  669. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  670. if (DateTime.UtcNow < cacheExpirationDate)
  671. {
  672. return true;
  673. }
  674. }
  675. return false;
  676. }
  677. /// <summary>
  678. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  679. /// </summary>
  680. /// <param name="date">The date.</param>
  681. /// <returns>DateTime.</returns>
  682. private DateTime NormalizeDateForComparison(DateTime date)
  683. {
  684. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  685. }
  686. /// <summary>
  687. /// Adds the response headers.
  688. /// </summary>
  689. /// <param name="hasHeaders">The has options.</param>
  690. /// <param name="responseHeaders">The response headers.</param>
  691. private void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  692. {
  693. foreach (var item in responseHeaders)
  694. {
  695. hasHeaders.Headers[item.Key] = item.Value;
  696. }
  697. }
  698. }
  699. }