HttpResultFactory.cs 27 KB

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