HttpResultFactory.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.IO.Compression;
  7. using System.Net;
  8. using System.Runtime.Serialization;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Xml;
  12. using Emby.Server.Implementations.Services;
  13. using MediaBrowser.Controller.Net;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.Serialization;
  16. using MediaBrowser.Model.Services;
  17. using Microsoft.Extensions.Logging;
  18. using Microsoft.Extensions.Primitives;
  19. using Microsoft.Net.Http.Headers;
  20. using IRequest = MediaBrowser.Model.Services.IRequest;
  21. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  22. namespace Emby.Server.Implementations.HttpServer
  23. {
  24. /// <summary>
  25. /// Class HttpResultFactory.
  26. /// </summary>
  27. public class HttpResultFactory : IHttpResultFactory
  28. {
  29. // Last-Modified and If-Modified-Since must follow strict date format,
  30. // see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since
  31. private const string HttpDateFormat = "ddd, dd MMM yyyy HH:mm:ss \"GMT\"";
  32. // We specifically use en-US culture because both day of week and month names require it
  33. private static readonly CultureInfo _enUSculture = new CultureInfo("en-US", false);
  34. /// <summary>
  35. /// The logger.
  36. /// </summary>
  37. private readonly ILogger<HttpResultFactory> _logger;
  38. private readonly IFileSystem _fileSystem;
  39. private readonly IJsonSerializer _jsonSerializer;
  40. private readonly IStreamHelper _streamHelper;
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
  43. /// </summary>
  44. public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IStreamHelper streamHelper)
  45. {
  46. _fileSystem = fileSystem;
  47. _jsonSerializer = jsonSerializer;
  48. _streamHelper = streamHelper;
  49. _logger = loggerfactory.CreateLogger<HttpResultFactory>();
  50. }
  51. /// <summary>
  52. /// Gets the result.
  53. /// </summary>
  54. /// <param name="requestContext">The request context.</param>
  55. /// <param name="content">The content.</param>
  56. /// <param name="contentType">Type of the content.</param>
  57. /// <param name="responseHeaders">The response headers.</param>
  58. /// <returns>System.Object.</returns>
  59. public object GetResult(IRequest requestContext, byte[] content, string contentType, IDictionary<string, string> responseHeaders = null)
  60. {
  61. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  62. }
  63. public object GetResult(string content, string contentType, IDictionary<string, string> responseHeaders = null)
  64. {
  65. return GetHttpResult(null, content, contentType, true, responseHeaders);
  66. }
  67. public object GetResult(IRequest requestContext, Stream content, string contentType, IDictionary<string, string> responseHeaders = null)
  68. {
  69. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  70. }
  71. public object GetResult(IRequest requestContext, string content, string contentType, IDictionary<string, string> responseHeaders = null)
  72. {
  73. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  74. }
  75. public object GetRedirectResult(string url)
  76. {
  77. var responseHeaders = new Dictionary<string, string>();
  78. responseHeaders[HeaderNames.Location] = url;
  79. var result = new HttpResult(Array.Empty<byte>(), "text/plain", HttpStatusCode.Redirect);
  80. AddResponseHeaders(result, responseHeaders);
  81. return result;
  82. }
  83. /// <summary>
  84. /// Gets the HTTP result.
  85. /// </summary>
  86. private IHasHeaders GetHttpResult(IRequest requestContext, Stream content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  87. {
  88. var result = new StreamWriter(content, contentType);
  89. if (responseHeaders == null)
  90. {
  91. responseHeaders = new Dictionary<string, string>();
  92. }
  93. if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string expires))
  94. {
  95. responseHeaders[HeaderNames.Expires] = "0";
  96. }
  97. AddResponseHeaders(result, responseHeaders);
  98. return result;
  99. }
  100. /// <summary>
  101. /// Gets the HTTP result.
  102. /// </summary>
  103. private IHasHeaders GetHttpResult(IRequest requestContext, byte[] content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  104. {
  105. string compressionType = null;
  106. bool isHeadRequest = false;
  107. if (requestContext != null)
  108. {
  109. compressionType = GetCompressionType(requestContext, content, contentType);
  110. isHeadRequest = string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase);
  111. }
  112. IHasHeaders result;
  113. if (string.IsNullOrEmpty(compressionType))
  114. {
  115. var contentLength = content.Length;
  116. if (isHeadRequest)
  117. {
  118. content = Array.Empty<byte>();
  119. }
  120. result = new StreamWriter(content, contentType, contentLength);
  121. }
  122. else
  123. {
  124. result = GetCompressedResult(content, compressionType, responseHeaders, isHeadRequest, contentType);
  125. }
  126. if (responseHeaders == null)
  127. {
  128. responseHeaders = new Dictionary<string, string>();
  129. }
  130. if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string _))
  131. {
  132. responseHeaders[HeaderNames.Expires] = "0";
  133. }
  134. AddResponseHeaders(result, responseHeaders);
  135. return result;
  136. }
  137. /// <summary>
  138. /// Gets the HTTP result.
  139. /// </summary>
  140. private IHasHeaders GetHttpResult(IRequest requestContext, string content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  141. {
  142. IHasHeaders result;
  143. var bytes = Encoding.UTF8.GetBytes(content);
  144. var compressionType = requestContext == null ? null : GetCompressionType(requestContext, bytes, contentType);
  145. var isHeadRequest = requestContext == null ? false : string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase);
  146. if (string.IsNullOrEmpty(compressionType))
  147. {
  148. var contentLength = bytes.Length;
  149. if (isHeadRequest)
  150. {
  151. bytes = Array.Empty<byte>();
  152. }
  153. result = new StreamWriter(bytes, contentType, contentLength);
  154. }
  155. else
  156. {
  157. result = GetCompressedResult(bytes, compressionType, responseHeaders, isHeadRequest, contentType);
  158. }
  159. if (responseHeaders == null)
  160. {
  161. responseHeaders = new Dictionary<string, string>();
  162. }
  163. if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string _))
  164. {
  165. responseHeaders[HeaderNames.Expires] = "0";
  166. }
  167. AddResponseHeaders(result, responseHeaders);
  168. return result;
  169. }
  170. /// <summary>
  171. /// Gets the optimized result.
  172. /// </summary>
  173. /// <typeparam name="T"></typeparam>
  174. public object GetResult<T>(IRequest requestContext, T result, IDictionary<string, string> responseHeaders = null)
  175. where T : class
  176. {
  177. if (result == null)
  178. {
  179. throw new ArgumentNullException(nameof(result));
  180. }
  181. if (responseHeaders == null)
  182. {
  183. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  184. }
  185. responseHeaders[HeaderNames.Expires] = "0";
  186. return ToOptimizedResultInternal(requestContext, result, responseHeaders);
  187. }
  188. private string GetCompressionType(IRequest request, byte[] content, string responseContentType)
  189. {
  190. if (responseContentType == null)
  191. {
  192. return null;
  193. }
  194. // Per apple docs, hls manifests must be compressed
  195. if (!responseContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) &&
  196. responseContentType.IndexOf("json", StringComparison.OrdinalIgnoreCase) == -1 &&
  197. responseContentType.IndexOf("javascript", StringComparison.OrdinalIgnoreCase) == -1 &&
  198. responseContentType.IndexOf("xml", StringComparison.OrdinalIgnoreCase) == -1 &&
  199. responseContentType.IndexOf("application/x-mpegURL", StringComparison.OrdinalIgnoreCase) == -1)
  200. {
  201. return null;
  202. }
  203. if (content.Length < 1024)
  204. {
  205. return null;
  206. }
  207. return GetCompressionType(request);
  208. }
  209. private static string GetCompressionType(IRequest request)
  210. {
  211. var acceptEncoding = request.Headers[HeaderNames.AcceptEncoding].ToString();
  212. if (!string.IsNullOrEmpty(acceptEncoding))
  213. {
  214. // if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
  215. // return "br";
  216. if (acceptEncoding.Contains("deflate", StringComparison.OrdinalIgnoreCase))
  217. {
  218. return "deflate";
  219. }
  220. if (acceptEncoding.Contains("gzip", StringComparison.OrdinalIgnoreCase))
  221. {
  222. return "gzip";
  223. }
  224. }
  225. return null;
  226. }
  227. /// <summary>
  228. /// Returns the optimized result for the IRequestContext.
  229. /// Does not use or store results in any cache.
  230. /// </summary>
  231. /// <param name="request"></param>
  232. /// <param name="dto"></param>
  233. /// <returns></returns>
  234. public object ToOptimizedResult<T>(IRequest request, T dto)
  235. {
  236. return ToOptimizedResultInternal(request, dto);
  237. }
  238. private object ToOptimizedResultInternal<T>(IRequest request, T dto, IDictionary<string, string> responseHeaders = null)
  239. {
  240. // TODO: @bond use Span and .Equals
  241. var contentType = request.ResponseContentType?.Split(';')[0].Trim().ToLowerInvariant();
  242. switch (contentType)
  243. {
  244. case "application/xml":
  245. case "text/xml":
  246. case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
  247. return GetHttpResult(request, SerializeToXmlString(dto), contentType, false, responseHeaders);
  248. case "application/json":
  249. case "text/json":
  250. return GetHttpResult(request, _jsonSerializer.SerializeToString(dto), contentType, false, responseHeaders);
  251. default:
  252. break;
  253. }
  254. var isHeadRequest = string.Equals(request.Verb, "head", StringComparison.OrdinalIgnoreCase);
  255. var ms = new MemoryStream();
  256. var writerFn = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
  257. writerFn(dto, ms);
  258. ms.Position = 0;
  259. if (isHeadRequest)
  260. {
  261. using (ms)
  262. {
  263. return GetHttpResult(request, Array.Empty<byte>(), contentType, true, responseHeaders);
  264. }
  265. }
  266. return GetHttpResult(request, ms, contentType, true, responseHeaders);
  267. }
  268. private IHasHeaders GetCompressedResult(byte[] content,
  269. string requestedCompressionType,
  270. IDictionary<string, string> responseHeaders,
  271. bool isHeadRequest,
  272. string contentType)
  273. {
  274. if (responseHeaders == null)
  275. {
  276. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  277. }
  278. content = Compress(content, requestedCompressionType);
  279. responseHeaders[HeaderNames.ContentEncoding] = requestedCompressionType;
  280. responseHeaders[HeaderNames.Vary] = HeaderNames.AcceptEncoding;
  281. var contentLength = content.Length;
  282. if (isHeadRequest)
  283. {
  284. var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength);
  285. AddResponseHeaders(result, responseHeaders);
  286. return result;
  287. }
  288. else
  289. {
  290. var result = new StreamWriter(content, contentType, contentLength);
  291. AddResponseHeaders(result, responseHeaders);
  292. return result;
  293. }
  294. }
  295. private byte[] Compress(byte[] bytes, string compressionType)
  296. {
  297. if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
  298. {
  299. return Deflate(bytes);
  300. }
  301. if (string.Equals(compressionType, "gzip", StringComparison.OrdinalIgnoreCase))
  302. {
  303. return GZip(bytes);
  304. }
  305. throw new NotSupportedException(compressionType);
  306. }
  307. private static byte[] Deflate(byte[] bytes)
  308. {
  309. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  310. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  311. using (var ms = new MemoryStream())
  312. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  313. {
  314. zipStream.Write(bytes, 0, bytes.Length);
  315. zipStream.Dispose();
  316. return ms.ToArray();
  317. }
  318. }
  319. private static byte[] GZip(byte[] buffer)
  320. {
  321. using (var ms = new MemoryStream())
  322. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  323. {
  324. zipStream.Write(buffer, 0, buffer.Length);
  325. zipStream.Dispose();
  326. return ms.ToArray();
  327. }
  328. }
  329. private static string SerializeToXmlString(object from)
  330. {
  331. using (var ms = new MemoryStream())
  332. {
  333. var xwSettings = new XmlWriterSettings();
  334. xwSettings.Encoding = new UTF8Encoding(false);
  335. xwSettings.OmitXmlDeclaration = false;
  336. using (var xw = XmlWriter.Create(ms, xwSettings))
  337. {
  338. var serializer = new DataContractSerializer(from.GetType());
  339. serializer.WriteObject(xw, from);
  340. xw.Flush();
  341. ms.Seek(0, SeekOrigin.Begin);
  342. using (var reader = new StreamReader(ms))
  343. {
  344. return reader.ReadToEnd();
  345. }
  346. }
  347. }
  348. }
  349. /// <summary>
  350. /// Pres the process optimized result.
  351. /// </summary>
  352. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options)
  353. {
  354. bool noCache = (requestContext.Headers[HeaderNames.CacheControl].ToString()).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
  355. AddCachingHeaders(responseHeaders, options.CacheDuration, noCache, options.DateLastModified);
  356. if (!noCache)
  357. {
  358. if (!DateTime.TryParseExact(requestContext.Headers[HeaderNames.IfModifiedSince], HttpDateFormat, _enUSculture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var ifModifiedSinceHeader))
  359. {
  360. _logger.LogDebug("Failed to parse If-Modified-Since header date: {0}", requestContext.Headers[HeaderNames.IfModifiedSince]);
  361. return null;
  362. }
  363. if (IsNotModified(ifModifiedSinceHeader, options.CacheDuration, options.DateLastModified))
  364. {
  365. AddAgeHeader(responseHeaders, options.DateLastModified);
  366. var result = new HttpResult(Array.Empty<byte>(), options.ContentType ?? "text/html", HttpStatusCode.NotModified);
  367. AddResponseHeaders(result, responseHeaders);
  368. return result;
  369. }
  370. }
  371. return null;
  372. }
  373. public Task<object> GetStaticFileResult(IRequest requestContext,
  374. string path,
  375. FileShare fileShare = FileShare.Read)
  376. {
  377. if (string.IsNullOrEmpty(path))
  378. {
  379. throw new ArgumentNullException(nameof(path));
  380. }
  381. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  382. {
  383. Path = path,
  384. FileShare = fileShare
  385. });
  386. }
  387. public Task<object> GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options)
  388. {
  389. var path = options.Path;
  390. var fileShare = options.FileShare;
  391. if (string.IsNullOrEmpty(path))
  392. {
  393. throw new ArgumentException("Path can't be empty.", nameof(options));
  394. }
  395. if (fileShare != FileShare.Read && fileShare != FileShare.ReadWrite)
  396. {
  397. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  398. }
  399. if (string.IsNullOrEmpty(options.ContentType))
  400. {
  401. options.ContentType = MimeTypes.GetMimeType(path);
  402. }
  403. if (!options.DateLastModified.HasValue)
  404. {
  405. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  406. }
  407. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  408. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  409. return GetStaticResult(requestContext, options);
  410. }
  411. /// <summary>
  412. /// Gets the file stream.
  413. /// </summary>
  414. /// <param name="path">The path.</param>
  415. /// <param name="fileShare">The file share.</param>
  416. /// <returns>Stream.</returns>
  417. private Stream GetFileStream(string path, FileShare fileShare)
  418. {
  419. return new FileStream(path, FileMode.Open, FileAccess.Read, fileShare);
  420. }
  421. public Task<object> GetStaticResult(IRequest requestContext,
  422. Guid cacheKey,
  423. DateTime? lastDateModified,
  424. TimeSpan? cacheDuration,
  425. string contentType,
  426. Func<Task<Stream>> factoryFn,
  427. IDictionary<string, string> responseHeaders = null,
  428. bool isHeadRequest = false)
  429. {
  430. return GetStaticResult(requestContext, new StaticResultOptions
  431. {
  432. CacheDuration = cacheDuration,
  433. ContentFactory = factoryFn,
  434. ContentType = contentType,
  435. DateLastModified = lastDateModified,
  436. IsHeadRequest = isHeadRequest,
  437. ResponseHeaders = responseHeaders
  438. });
  439. }
  440. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  441. {
  442. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  443. var contentType = options.ContentType;
  444. if (!StringValues.IsNullOrEmpty(requestContext.Headers[HeaderNames.IfModifiedSince]))
  445. {
  446. // See if the result is already cached in the browser
  447. var result = GetCachedResult(requestContext, options.ResponseHeaders, options);
  448. if (result != null)
  449. {
  450. return result;
  451. }
  452. }
  453. // TODO: We don't really need the option value
  454. var isHeadRequest = options.IsHeadRequest || string.Equals(requestContext.Verb, "HEAD", StringComparison.OrdinalIgnoreCase);
  455. var factoryFn = options.ContentFactory;
  456. var responseHeaders = options.ResponseHeaders;
  457. AddCachingHeaders(responseHeaders, options.CacheDuration, false, options.DateLastModified);
  458. AddAgeHeader(responseHeaders, options.DateLastModified);
  459. var rangeHeader = requestContext.Headers[HeaderNames.Range];
  460. if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
  461. {
  462. var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem, _streamHelper)
  463. {
  464. OnComplete = options.OnComplete,
  465. OnError = options.OnError,
  466. FileShare = options.FileShare
  467. };
  468. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  469. return hasHeaders;
  470. }
  471. var stream = await factoryFn().ConfigureAwait(false);
  472. var totalContentLength = options.ContentLength;
  473. if (!totalContentLength.HasValue)
  474. {
  475. try
  476. {
  477. totalContentLength = stream.Length;
  478. }
  479. catch (NotSupportedException)
  480. {
  481. }
  482. }
  483. if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue)
  484. {
  485. var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest, _logger)
  486. {
  487. OnComplete = options.OnComplete
  488. };
  489. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  490. return hasHeaders;
  491. }
  492. else
  493. {
  494. if (totalContentLength.HasValue)
  495. {
  496. responseHeaders["Content-Length"] = totalContentLength.Value.ToString(CultureInfo.InvariantCulture);
  497. }
  498. if (isHeadRequest)
  499. {
  500. using (stream)
  501. {
  502. return GetHttpResult(requestContext, Array.Empty<byte>(), contentType, true, responseHeaders);
  503. }
  504. }
  505. var hasHeaders = new StreamWriter(stream, contentType)
  506. {
  507. OnComplete = options.OnComplete,
  508. OnError = options.OnError
  509. };
  510. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  511. return hasHeaders;
  512. }
  513. }
  514. /// <summary>
  515. /// Adds the caching responseHeaders.
  516. /// </summary>
  517. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, TimeSpan? cacheDuration,
  518. bool noCache, DateTime? lastModifiedDate)
  519. {
  520. if (noCache)
  521. {
  522. responseHeaders[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";
  523. responseHeaders[HeaderNames.Pragma] = "no-cache, no-store, must-revalidate";
  524. return;
  525. }
  526. if (cacheDuration.HasValue)
  527. {
  528. responseHeaders[HeaderNames.CacheControl] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
  529. }
  530. else
  531. {
  532. responseHeaders[HeaderNames.CacheControl] = "public";
  533. }
  534. if (lastModifiedDate.HasValue)
  535. {
  536. responseHeaders[HeaderNames.LastModified] = lastModifiedDate.Value.ToUniversalTime().ToString(HttpDateFormat, _enUSculture);
  537. }
  538. }
  539. /// <summary>
  540. /// Adds the age header.
  541. /// </summary>
  542. /// <param name="responseHeaders">The responseHeaders.</param>
  543. /// <param name="lastDateModified">The last date modified.</param>
  544. private static void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  545. {
  546. if (lastDateModified.HasValue)
  547. {
  548. responseHeaders[HeaderNames.Age] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  549. }
  550. }
  551. /// <summary>
  552. /// Determines whether [is not modified] [the specified if modified since].
  553. /// </summary>
  554. /// <param name="ifModifiedSince">If modified since.</param>
  555. /// <param name="cacheDuration">Duration of the cache.</param>
  556. /// <param name="dateModified">The date modified.</param>
  557. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  558. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  559. {
  560. if (dateModified.HasValue)
  561. {
  562. var lastModified = NormalizeDateForComparison(dateModified.Value);
  563. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  564. return lastModified <= ifModifiedSince;
  565. }
  566. if (cacheDuration.HasValue)
  567. {
  568. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  569. if (DateTime.UtcNow < cacheExpirationDate)
  570. {
  571. return true;
  572. }
  573. }
  574. return false;
  575. }
  576. /// <summary>
  577. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  578. /// </summary>
  579. /// <param name="date">The date.</param>
  580. /// <returns>DateTime.</returns>
  581. private static DateTime NormalizeDateForComparison(DateTime date)
  582. {
  583. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  584. }
  585. /// <summary>
  586. /// Adds the response headers.
  587. /// </summary>
  588. /// <param name="hasHeaders">The has options.</param>
  589. /// <param name="responseHeaders">The response headers.</param>
  590. private static void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  591. {
  592. foreach (var item in responseHeaders)
  593. {
  594. hasHeaders.Headers[item.Key] = item.Value;
  595. }
  596. }
  597. }
  598. }