HttpResultFactory.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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. /// <param name="requestContext">The request context.</param>
  304. /// <param name="responseHeaders">The responseHeaders.</param>
  305. /// <param name="cacheKey">The cache key.</param>
  306. /// <param name="cacheKeyString">The cache key string.</param>
  307. /// <param name="lastDateModified">The last date modified.</param>
  308. /// <param name="cacheDuration">Duration of the cache.</param>
  309. /// <param name="contentType">Type of the content.</param>
  310. /// <returns>System.Object.</returns>
  311. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  312. {
  313. responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString);
  314. if (IsNotModified(requestContext, cacheKey, lastDateModified, cacheDuration))
  315. {
  316. AddAgeHeader(responseHeaders, lastDateModified);
  317. AddExpiresHeader(responseHeaders, cacheKeyString, cacheDuration);
  318. var result = new HttpResult(new byte[] { }, contentType ?? "text/html", HttpStatusCode.NotModified);
  319. AddResponseHeaders(result, responseHeaders);
  320. return result;
  321. }
  322. AddCachingHeaders(responseHeaders, cacheKeyString, lastDateModified, cacheDuration);
  323. return null;
  324. }
  325. public Task<object> GetStaticFileResult(IRequest requestContext,
  326. string path,
  327. FileShareMode fileShare = FileShareMode.Read)
  328. {
  329. if (string.IsNullOrEmpty(path))
  330. {
  331. throw new ArgumentNullException("path");
  332. }
  333. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  334. {
  335. Path = path,
  336. FileShare = fileShare
  337. });
  338. }
  339. public Task<object> GetStaticFileResult(IRequest requestContext,
  340. StaticFileResultOptions options)
  341. {
  342. var path = options.Path;
  343. var fileShare = options.FileShare;
  344. if (string.IsNullOrEmpty(path))
  345. {
  346. throw new ArgumentNullException("path");
  347. }
  348. if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
  349. {
  350. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  351. }
  352. if (string.IsNullOrWhiteSpace(options.ContentType))
  353. {
  354. options.ContentType = MimeTypes.GetMimeType(path);
  355. }
  356. if (!options.DateLastModified.HasValue)
  357. {
  358. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  359. }
  360. var cacheKey = path + options.DateLastModified.Value.Ticks;
  361. options.CacheKey = cacheKey.GetMD5();
  362. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  363. return GetStaticResult(requestContext, options);
  364. }
  365. /// <summary>
  366. /// Gets the file stream.
  367. /// </summary>
  368. /// <param name="path">The path.</param>
  369. /// <param name="fileShare">The file share.</param>
  370. /// <returns>Stream.</returns>
  371. private Stream GetFileStream(string path, FileShareMode fileShare)
  372. {
  373. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  374. }
  375. public Task<object> GetStaticResult(IRequest requestContext,
  376. Guid cacheKey,
  377. DateTime? lastDateModified,
  378. TimeSpan? cacheDuration,
  379. string contentType,
  380. Func<Task<Stream>> factoryFn,
  381. IDictionary<string, string> responseHeaders = null,
  382. bool isHeadRequest = false)
  383. {
  384. return GetStaticResult(requestContext, new StaticResultOptions
  385. {
  386. CacheDuration = cacheDuration,
  387. CacheKey = cacheKey,
  388. ContentFactory = factoryFn,
  389. ContentType = contentType,
  390. DateLastModified = lastDateModified,
  391. IsHeadRequest = isHeadRequest,
  392. ResponseHeaders = responseHeaders
  393. });
  394. }
  395. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  396. {
  397. var cacheKey = options.CacheKey;
  398. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  399. var contentType = options.ContentType;
  400. if (cacheKey == Guid.Empty)
  401. {
  402. throw new ArgumentNullException("cacheKey");
  403. }
  404. var key = cacheKey.ToString("N");
  405. // See if the result is already cached in the browser
  406. var result = GetCachedResult(requestContext, options.ResponseHeaders, cacheKey, key, options.DateLastModified, options.CacheDuration, contentType);
  407. if (result != null)
  408. {
  409. return result;
  410. }
  411. var compress = ShouldCompressResponse(requestContext, contentType);
  412. var hasHeaders = await GetStaticResult(requestContext, options, compress).ConfigureAwait(false);
  413. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  414. return hasHeaders;
  415. }
  416. /// <summary>
  417. /// Shoulds the compress response.
  418. /// </summary>
  419. /// <param name="requestContext">The request context.</param>
  420. /// <param name="contentType">Type of the content.</param>
  421. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  422. private bool ShouldCompressResponse(IRequest requestContext, string contentType)
  423. {
  424. // It will take some work to support compression with byte range requests
  425. if (!string.IsNullOrEmpty(requestContext.Headers.Get("Range")))
  426. {
  427. return false;
  428. }
  429. // Don't compress media
  430. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  431. {
  432. return false;
  433. }
  434. // Don't compress images
  435. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  436. {
  437. return false;
  438. }
  439. if (contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  440. {
  441. return false;
  442. }
  443. if (contentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase))
  444. {
  445. if (string.Equals(contentType, "application/x-javascript", StringComparison.OrdinalIgnoreCase))
  446. {
  447. return true;
  448. }
  449. if (string.Equals(contentType, "application/xml", StringComparison.OrdinalIgnoreCase))
  450. {
  451. return true;
  452. }
  453. return false;
  454. }
  455. return true;
  456. }
  457. /// <summary>
  458. /// The us culture
  459. /// </summary>
  460. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  461. private async Task<IHasHeaders> GetStaticResult(IRequest requestContext, StaticResultOptions options, bool compress)
  462. {
  463. var isHeadRequest = options.IsHeadRequest;
  464. var factoryFn = options.ContentFactory;
  465. var contentType = options.ContentType;
  466. var responseHeaders = options.ResponseHeaders;
  467. var requestedCompressionType = GetCompressionType(requestContext);
  468. if (!compress || string.IsNullOrEmpty(requestedCompressionType))
  469. {
  470. var rangeHeader = requestContext.Headers.Get("Range");
  471. if (!isHeadRequest && !string.IsNullOrWhiteSpace(options.Path) && options.FileShare == FileShareMode.Read)
  472. {
  473. return new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
  474. {
  475. OnComplete = options.OnComplete,
  476. OnError = options.OnError
  477. };
  478. }
  479. if (!string.IsNullOrEmpty(rangeHeader))
  480. {
  481. var stream = await factoryFn().ConfigureAwait(false);
  482. return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest, _logger)
  483. {
  484. OnComplete = options.OnComplete
  485. };
  486. }
  487. else
  488. {
  489. var stream = await factoryFn().ConfigureAwait(false);
  490. responseHeaders["Content-Length"] = stream.Length.ToString(UsCulture);
  491. if (isHeadRequest)
  492. {
  493. stream.Dispose();
  494. return GetHttpResult(new byte[] { }, contentType, true);
  495. }
  496. return new StreamWriter(stream, contentType, _logger)
  497. {
  498. OnComplete = options.OnComplete,
  499. OnError = options.OnError
  500. };
  501. }
  502. }
  503. using (var stream = await factoryFn().ConfigureAwait(false))
  504. {
  505. return await GetCompressedResult(stream, requestedCompressionType, responseHeaders, isHeadRequest, contentType).ConfigureAwait(false);
  506. }
  507. }
  508. private async Task<IHasHeaders> GetCompressedResult(Stream stream,
  509. string requestedCompressionType,
  510. IDictionary<string,string> responseHeaders,
  511. bool isHeadRequest,
  512. string contentType)
  513. {
  514. using (var reader = new MemoryStream())
  515. {
  516. await stream.CopyToAsync(reader).ConfigureAwait(false);
  517. reader.Position = 0;
  518. var content = reader.ToArray();
  519. if (content.Length >= 1024)
  520. {
  521. content = Compress(content, requestedCompressionType);
  522. responseHeaders["Content-Encoding"] = requestedCompressionType;
  523. }
  524. responseHeaders["Content-Length"] = content.Length.ToString(UsCulture);
  525. if (isHeadRequest)
  526. {
  527. return GetHttpResult(new byte[] { }, contentType, true);
  528. }
  529. return GetHttpResult(content, contentType, true, responseHeaders);
  530. }
  531. }
  532. private byte[] Compress(byte[] bytes, string compressionType)
  533. {
  534. if (compressionType == "deflate")
  535. return Deflate(bytes);
  536. if (compressionType == "gzip")
  537. return GZip(bytes);
  538. throw new NotSupportedException(compressionType);
  539. }
  540. private byte[] Deflate(byte[] bytes)
  541. {
  542. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  543. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  544. using (var ms = new MemoryStream())
  545. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  546. {
  547. zipStream.Write(bytes, 0, bytes.Length);
  548. zipStream.Dispose();
  549. return ms.ToArray();
  550. }
  551. }
  552. private 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.Dispose();
  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.Headers.Get("If-Modified-Since");
  634. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  635. {
  636. DateTime ifModifiedSince;
  637. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  638. {
  639. if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  640. {
  641. return true;
  642. }
  643. }
  644. }
  645. var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match");
  646. // Validate If-None-Match
  647. if ((cacheKey.HasValue || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  648. {
  649. Guid ifNoneMatch;
  650. ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"');
  651. if (Guid.TryParse(ifNoneMatchHeader, out ifNoneMatch))
  652. {
  653. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  654. {
  655. return true;
  656. }
  657. }
  658. }
  659. return false;
  660. }
  661. /// <summary>
  662. /// Determines whether [is not modified] [the specified if modified since].
  663. /// </summary>
  664. /// <param name="ifModifiedSince">If modified since.</param>
  665. /// <param name="cacheDuration">Duration of the cache.</param>
  666. /// <param name="dateModified">The date modified.</param>
  667. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  668. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  669. {
  670. if (dateModified.HasValue)
  671. {
  672. var lastModified = NormalizeDateForComparison(dateModified.Value);
  673. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  674. return lastModified <= ifModifiedSince;
  675. }
  676. if (cacheDuration.HasValue)
  677. {
  678. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  679. if (DateTime.UtcNow < cacheExpirationDate)
  680. {
  681. return true;
  682. }
  683. }
  684. return false;
  685. }
  686. /// <summary>
  687. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  688. /// </summary>
  689. /// <param name="date">The date.</param>
  690. /// <returns>DateTime.</returns>
  691. private DateTime NormalizeDateForComparison(DateTime date)
  692. {
  693. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  694. }
  695. /// <summary>
  696. /// Adds the response headers.
  697. /// </summary>
  698. /// <param name="hasHeaders">The has options.</param>
  699. /// <param name="responseHeaders">The response headers.</param>
  700. private void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  701. {
  702. foreach (var item in responseHeaders)
  703. {
  704. hasHeaders.Headers[item.Key] = item.Value;
  705. }
  706. }
  707. }
  708. }