HttpResultFactory.cs 31 KB

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