HttpResultFactory.cs 31 KB

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