HttpResultFactory.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  368. // Quotes are valid in linux. They'll possibly cause issues here
  369. var filename = (Path.GetFileName(path) ?? string.Empty).Replace("\"", string.Empty);
  370. if (!string.IsNullOrWhiteSpace(filename))
  371. {
  372. options.ResponseHeaders["Content-Disposition"] = "inline; filename=\"" + filename + "\"";
  373. }
  374. return GetStaticResult(requestContext, options);
  375. }
  376. /// <summary>
  377. /// Gets the file stream.
  378. /// </summary>
  379. /// <param name="path">The path.</param>
  380. /// <param name="fileShare">The file share.</param>
  381. /// <returns>Stream.</returns>
  382. private Stream GetFileStream(string path, FileShareMode fileShare)
  383. {
  384. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  385. }
  386. public Task<object> GetStaticResult(IRequest requestContext,
  387. Guid cacheKey,
  388. DateTime? lastDateModified,
  389. TimeSpan? cacheDuration,
  390. string contentType,
  391. Func<Task<Stream>> factoryFn,
  392. IDictionary<string, string> responseHeaders = null,
  393. bool isHeadRequest = false)
  394. {
  395. return GetStaticResult(requestContext, new StaticResultOptions
  396. {
  397. CacheDuration = cacheDuration,
  398. CacheKey = cacheKey,
  399. ContentFactory = factoryFn,
  400. ContentType = contentType,
  401. DateLastModified = lastDateModified,
  402. IsHeadRequest = isHeadRequest,
  403. ResponseHeaders = responseHeaders
  404. });
  405. }
  406. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  407. {
  408. var cacheKey = options.CacheKey;
  409. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  410. var contentType = options.ContentType;
  411. if (cacheKey == Guid.Empty)
  412. {
  413. throw new ArgumentNullException("cacheKey");
  414. }
  415. var key = cacheKey.ToString("N");
  416. // See if the result is already cached in the browser
  417. var result = GetCachedResult(requestContext, options.ResponseHeaders, cacheKey, key, options.DateLastModified, options.CacheDuration, contentType);
  418. if (result != null)
  419. {
  420. return result;
  421. }
  422. var compress = ShouldCompressResponse(requestContext, contentType);
  423. var hasHeaders = await GetStaticResult(requestContext, options, compress).ConfigureAwait(false);
  424. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  425. return hasHeaders;
  426. }
  427. /// <summary>
  428. /// Shoulds the compress response.
  429. /// </summary>
  430. /// <param name="requestContext">The request context.</param>
  431. /// <param name="contentType">Type of the content.</param>
  432. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  433. private bool ShouldCompressResponse(IRequest requestContext, string contentType)
  434. {
  435. // It will take some work to support compression with byte range requests
  436. if (!string.IsNullOrWhiteSpace(requestContext.Headers.Get("Range")))
  437. {
  438. return false;
  439. }
  440. // Don't compress media
  441. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  442. {
  443. return false;
  444. }
  445. // Don't compress images
  446. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  447. {
  448. return false;
  449. }
  450. if (contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  451. {
  452. return false;
  453. }
  454. if (contentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase))
  455. {
  456. if (string.Equals(contentType, "application/x-javascript", StringComparison.OrdinalIgnoreCase))
  457. {
  458. return true;
  459. }
  460. if (string.Equals(contentType, "application/xml", StringComparison.OrdinalIgnoreCase))
  461. {
  462. return true;
  463. }
  464. return false;
  465. }
  466. return true;
  467. }
  468. /// <summary>
  469. /// The us culture
  470. /// </summary>
  471. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  472. private async Task<IHasHeaders> GetStaticResult(IRequest requestContext, StaticResultOptions options, bool compress)
  473. {
  474. var isHeadRequest = options.IsHeadRequest;
  475. var factoryFn = options.ContentFactory;
  476. var contentType = options.ContentType;
  477. var responseHeaders = options.ResponseHeaders;
  478. var requestedCompressionType = GetCompressionType(requestContext);
  479. if (!compress || string.IsNullOrEmpty(requestedCompressionType))
  480. {
  481. var rangeHeader = requestContext.Headers.Get("Range");
  482. if (!isHeadRequest && !string.IsNullOrWhiteSpace(options.Path))
  483. {
  484. return new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
  485. {
  486. OnComplete = options.OnComplete,
  487. OnError = options.OnError,
  488. FileShare = options.FileShare
  489. };
  490. }
  491. if (!string.IsNullOrWhiteSpace(rangeHeader))
  492. {
  493. var stream = await factoryFn().ConfigureAwait(false);
  494. return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest, _logger)
  495. {
  496. OnComplete = options.OnComplete
  497. };
  498. }
  499. else
  500. {
  501. var stream = await factoryFn().ConfigureAwait(false);
  502. responseHeaders["Content-Length"] = stream.Length.ToString(UsCulture);
  503. if (isHeadRequest)
  504. {
  505. stream.Dispose();
  506. return GetHttpResult(new byte[] { }, contentType, true);
  507. }
  508. return new StreamWriter(stream, contentType, _logger)
  509. {
  510. OnComplete = options.OnComplete,
  511. OnError = options.OnError
  512. };
  513. }
  514. }
  515. using (var stream = await factoryFn().ConfigureAwait(false))
  516. {
  517. return await GetCompressedResult(stream, requestedCompressionType, responseHeaders, isHeadRequest, contentType).ConfigureAwait(false);
  518. }
  519. }
  520. private async Task<IHasHeaders> GetCompressedResult(Stream stream,
  521. string requestedCompressionType,
  522. IDictionary<string, string> responseHeaders,
  523. bool isHeadRequest,
  524. string contentType)
  525. {
  526. using (var reader = new MemoryStream())
  527. {
  528. await stream.CopyToAsync(reader).ConfigureAwait(false);
  529. reader.Position = 0;
  530. var content = reader.ToArray();
  531. if (content.Length >= 1024)
  532. {
  533. content = Compress(content, requestedCompressionType);
  534. responseHeaders["Content-Encoding"] = requestedCompressionType;
  535. }
  536. responseHeaders["Vary"] = "Accept-Encoding";
  537. responseHeaders["Content-Length"] = content.Length.ToString(UsCulture);
  538. if (isHeadRequest)
  539. {
  540. return GetHttpResult(new byte[] { }, contentType, true);
  541. }
  542. return GetHttpResult(content, contentType, true, responseHeaders);
  543. }
  544. }
  545. private byte[] Compress(byte[] bytes, string compressionType)
  546. {
  547. if (compressionType == "deflate")
  548. return Deflate(bytes);
  549. if (compressionType == "gzip")
  550. return GZip(bytes);
  551. throw new NotSupportedException(compressionType);
  552. }
  553. private byte[] Deflate(byte[] bytes)
  554. {
  555. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  556. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  557. using (var ms = new MemoryStream())
  558. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  559. {
  560. zipStream.Write(bytes, 0, bytes.Length);
  561. zipStream.Dispose();
  562. return ms.ToArray();
  563. }
  564. }
  565. private byte[] GZip(byte[] buffer)
  566. {
  567. using (var ms = new MemoryStream())
  568. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  569. {
  570. zipStream.Write(buffer, 0, buffer.Length);
  571. zipStream.Dispose();
  572. return ms.ToArray();
  573. }
  574. }
  575. /// <summary>
  576. /// Adds the caching responseHeaders.
  577. /// </summary>
  578. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, bool noCache)
  579. {
  580. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  581. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  582. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  583. {
  584. AddAgeHeader(responseHeaders, lastDateModified);
  585. responseHeaders["Last-Modified"] = lastDateModified.Value.ToString("r");
  586. }
  587. if (!noCache && cacheDuration.HasValue)
  588. {
  589. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  590. }
  591. else if (!noCache && !string.IsNullOrEmpty(cacheKey))
  592. {
  593. responseHeaders["Cache-Control"] = "public";
  594. }
  595. else
  596. {
  597. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  598. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  599. }
  600. AddExpiresHeader(responseHeaders, cacheKey, cacheDuration, noCache);
  601. }
  602. /// <summary>
  603. /// Adds the expires header.
  604. /// </summary>
  605. private void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration, bool noCache)
  606. {
  607. if (!noCache && cacheDuration.HasValue)
  608. {
  609. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  610. }
  611. else if (string.IsNullOrEmpty(cacheKey))
  612. {
  613. responseHeaders["Expires"] = "-1";
  614. }
  615. }
  616. /// <summary>
  617. /// Adds the age header.
  618. /// </summary>
  619. /// <param name="responseHeaders">The responseHeaders.</param>
  620. /// <param name="lastDateModified">The last date modified.</param>
  621. private void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  622. {
  623. if (lastDateModified.HasValue)
  624. {
  625. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  626. }
  627. }
  628. /// <summary>
  629. /// Determines whether [is not modified] [the specified cache key].
  630. /// </summary>
  631. /// <param name="requestContext">The request context.</param>
  632. /// <param name="cacheKey">The cache key.</param>
  633. /// <param name="lastDateModified">The last date modified.</param>
  634. /// <param name="cacheDuration">Duration of the cache.</param>
  635. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  636. private bool IsNotModified(IRequest requestContext, Guid? cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  637. {
  638. //var isNotModified = true;
  639. var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since");
  640. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  641. {
  642. DateTime ifModifiedSince;
  643. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  644. {
  645. if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  646. {
  647. return true;
  648. }
  649. }
  650. }
  651. var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match");
  652. // Validate If-None-Match
  653. if ((cacheKey.HasValue || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  654. {
  655. Guid ifNoneMatch;
  656. ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"');
  657. if (Guid.TryParse(ifNoneMatchHeader, out ifNoneMatch))
  658. {
  659. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  660. {
  661. return true;
  662. }
  663. }
  664. }
  665. return false;
  666. }
  667. /// <summary>
  668. /// Determines whether [is not modified] [the specified if modified since].
  669. /// </summary>
  670. /// <param name="ifModifiedSince">If modified since.</param>
  671. /// <param name="cacheDuration">Duration of the cache.</param>
  672. /// <param name="dateModified">The date modified.</param>
  673. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  674. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  675. {
  676. if (dateModified.HasValue)
  677. {
  678. var lastModified = NormalizeDateForComparison(dateModified.Value);
  679. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  680. return lastModified <= ifModifiedSince;
  681. }
  682. if (cacheDuration.HasValue)
  683. {
  684. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  685. if (DateTime.UtcNow < cacheExpirationDate)
  686. {
  687. return true;
  688. }
  689. }
  690. return false;
  691. }
  692. /// <summary>
  693. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  694. /// </summary>
  695. /// <param name="date">The date.</param>
  696. /// <returns>DateTime.</returns>
  697. private DateTime NormalizeDateForComparison(DateTime date)
  698. {
  699. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  700. }
  701. /// <summary>
  702. /// Adds the response headers.
  703. /// </summary>
  704. /// <param name="hasHeaders">The has options.</param>
  705. /// <param name="responseHeaders">The response headers.</param>
  706. private void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  707. {
  708. foreach (var item in responseHeaders)
  709. {
  710. hasHeaders.Headers[item.Key] = item.Value;
  711. }
  712. }
  713. }
  714. }