HttpResultFactory.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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.IsNullOrWhiteSpace(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))
  472. {
  473. return new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
  474. {
  475. OnComplete = options.OnComplete,
  476. OnError = options.OnError,
  477. FileShare = options.FileShare
  478. };
  479. }
  480. if (!string.IsNullOrWhiteSpace(rangeHeader))
  481. {
  482. var stream = await factoryFn().ConfigureAwait(false);
  483. return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest, _logger)
  484. {
  485. OnComplete = options.OnComplete
  486. };
  487. }
  488. else
  489. {
  490. var stream = await factoryFn().ConfigureAwait(false);
  491. responseHeaders["Content-Length"] = stream.Length.ToString(UsCulture);
  492. if (isHeadRequest)
  493. {
  494. stream.Dispose();
  495. return GetHttpResult(new byte[] { }, contentType, true);
  496. }
  497. return new StreamWriter(stream, contentType, _logger)
  498. {
  499. OnComplete = options.OnComplete,
  500. OnError = options.OnError
  501. };
  502. }
  503. }
  504. using (var stream = await factoryFn().ConfigureAwait(false))
  505. {
  506. return await GetCompressedResult(stream, requestedCompressionType, responseHeaders, isHeadRequest, contentType).ConfigureAwait(false);
  507. }
  508. }
  509. private async Task<IHasHeaders> GetCompressedResult(Stream stream,
  510. string requestedCompressionType,
  511. IDictionary<string,string> responseHeaders,
  512. bool isHeadRequest,
  513. string contentType)
  514. {
  515. using (var reader = new MemoryStream())
  516. {
  517. await stream.CopyToAsync(reader).ConfigureAwait(false);
  518. reader.Position = 0;
  519. var content = reader.ToArray();
  520. if (content.Length >= 1024)
  521. {
  522. content = Compress(content, requestedCompressionType);
  523. responseHeaders["Content-Encoding"] = requestedCompressionType;
  524. }
  525. responseHeaders["Vary"] = "Accept-Encoding";
  526. responseHeaders["Content-Length"] = content.Length.ToString(UsCulture);
  527. if (isHeadRequest)
  528. {
  529. return GetHttpResult(new byte[] { }, contentType, true);
  530. }
  531. return GetHttpResult(content, contentType, true, responseHeaders);
  532. }
  533. }
  534. private byte[] Compress(byte[] bytes, string compressionType)
  535. {
  536. if (compressionType == "deflate")
  537. return Deflate(bytes);
  538. if (compressionType == "gzip")
  539. return GZip(bytes);
  540. throw new NotSupportedException(compressionType);
  541. }
  542. private byte[] Deflate(byte[] bytes)
  543. {
  544. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  545. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  546. using (var ms = new MemoryStream())
  547. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  548. {
  549. zipStream.Write(bytes, 0, bytes.Length);
  550. zipStream.Dispose();
  551. return ms.ToArray();
  552. }
  553. }
  554. private byte[] GZip(byte[] buffer)
  555. {
  556. using (var ms = new MemoryStream())
  557. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  558. {
  559. zipStream.Write(buffer, 0, buffer.Length);
  560. zipStream.Dispose();
  561. return ms.ToArray();
  562. }
  563. }
  564. /// <summary>
  565. /// Adds the caching responseHeaders.
  566. /// </summary>
  567. /// <param name="responseHeaders">The responseHeaders.</param>
  568. /// <param name="cacheKey">The cache key.</param>
  569. /// <param name="lastDateModified">The last date modified.</param>
  570. /// <param name="cacheDuration">Duration of the cache.</param>
  571. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  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 (cacheDuration.HasValue)
  581. {
  582. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  583. }
  584. else if (!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);
  594. }
  595. /// <summary>
  596. /// Adds the expires header.
  597. /// </summary>
  598. /// <param name="responseHeaders">The responseHeaders.</param>
  599. /// <param name="cacheKey">The cache key.</param>
  600. /// <param name="cacheDuration">Duration of the cache.</param>
  601. private void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration)
  602. {
  603. if (cacheDuration.HasValue)
  604. {
  605. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  606. }
  607. else if (string.IsNullOrEmpty(cacheKey))
  608. {
  609. responseHeaders["Expires"] = "-1";
  610. }
  611. }
  612. /// <summary>
  613. /// Adds the age header.
  614. /// </summary>
  615. /// <param name="responseHeaders">The responseHeaders.</param>
  616. /// <param name="lastDateModified">The last date modified.</param>
  617. private void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  618. {
  619. if (lastDateModified.HasValue)
  620. {
  621. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  622. }
  623. }
  624. /// <summary>
  625. /// Determines whether [is not modified] [the specified cache key].
  626. /// </summary>
  627. /// <param name="requestContext">The request context.</param>
  628. /// <param name="cacheKey">The cache key.</param>
  629. /// <param name="lastDateModified">The last date modified.</param>
  630. /// <param name="cacheDuration">Duration of the cache.</param>
  631. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  632. private bool IsNotModified(IRequest requestContext, Guid? cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  633. {
  634. //var isNotModified = true;
  635. var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since");
  636. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  637. {
  638. DateTime ifModifiedSince;
  639. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  640. {
  641. if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  642. {
  643. return true;
  644. }
  645. }
  646. }
  647. var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match");
  648. // Validate If-None-Match
  649. if ((cacheKey.HasValue || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  650. {
  651. Guid ifNoneMatch;
  652. ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"');
  653. if (Guid.TryParse(ifNoneMatchHeader, out ifNoneMatch))
  654. {
  655. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  656. {
  657. return true;
  658. }
  659. }
  660. }
  661. return false;
  662. }
  663. /// <summary>
  664. /// Determines whether [is not modified] [the specified if modified since].
  665. /// </summary>
  666. /// <param name="ifModifiedSince">If modified since.</param>
  667. /// <param name="cacheDuration">Duration of the cache.</param>
  668. /// <param name="dateModified">The date modified.</param>
  669. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  670. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  671. {
  672. if (dateModified.HasValue)
  673. {
  674. var lastModified = NormalizeDateForComparison(dateModified.Value);
  675. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  676. return lastModified <= ifModifiedSince;
  677. }
  678. if (cacheDuration.HasValue)
  679. {
  680. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  681. if (DateTime.UtcNow < cacheExpirationDate)
  682. {
  683. return true;
  684. }
  685. }
  686. return false;
  687. }
  688. /// <summary>
  689. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  690. /// </summary>
  691. /// <param name="date">The date.</param>
  692. /// <returns>DateTime.</returns>
  693. private DateTime NormalizeDateForComparison(DateTime date)
  694. {
  695. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  696. }
  697. /// <summary>
  698. /// Adds the response headers.
  699. /// </summary>
  700. /// <param name="hasHeaders">The has options.</param>
  701. /// <param name="responseHeaders">The response headers.</param>
  702. private void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  703. {
  704. foreach (var item in responseHeaders)
  705. {
  706. hasHeaders.Headers[item.Key] = item.Value;
  707. }
  708. }
  709. }
  710. }