HttpResultFactory.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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 _))
  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(
  269. byte[] content,
  270. string requestedCompressionType,
  271. IDictionary<string, string> responseHeaders,
  272. bool isHeadRequest,
  273. string contentType)
  274. {
  275. if (responseHeaders == null)
  276. {
  277. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  278. }
  279. content = Compress(content, requestedCompressionType);
  280. responseHeaders[HeaderNames.ContentEncoding] = requestedCompressionType;
  281. responseHeaders[HeaderNames.Vary] = HeaderNames.AcceptEncoding;
  282. var contentLength = content.Length;
  283. if (isHeadRequest)
  284. {
  285. var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength);
  286. AddResponseHeaders(result, responseHeaders);
  287. return result;
  288. }
  289. else
  290. {
  291. var result = new StreamWriter(content, contentType, contentLength);
  292. AddResponseHeaders(result, responseHeaders);
  293. return result;
  294. }
  295. }
  296. private byte[] Compress(byte[] bytes, string compressionType)
  297. {
  298. if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
  299. {
  300. return Deflate(bytes);
  301. }
  302. if (string.Equals(compressionType, "gzip", StringComparison.OrdinalIgnoreCase))
  303. {
  304. return GZip(bytes);
  305. }
  306. throw new NotSupportedException(compressionType);
  307. }
  308. private static byte[] Deflate(byte[] bytes)
  309. {
  310. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  311. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  312. using (var ms = new MemoryStream())
  313. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  314. {
  315. zipStream.Write(bytes, 0, bytes.Length);
  316. zipStream.Dispose();
  317. return ms.ToArray();
  318. }
  319. }
  320. private static byte[] GZip(byte[] buffer)
  321. {
  322. using (var ms = new MemoryStream())
  323. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  324. {
  325. zipStream.Write(buffer, 0, buffer.Length);
  326. zipStream.Dispose();
  327. return ms.ToArray();
  328. }
  329. }
  330. private static string SerializeToXmlString(object from)
  331. {
  332. using (var ms = new MemoryStream())
  333. {
  334. var xwSettings = new XmlWriterSettings();
  335. xwSettings.Encoding = new UTF8Encoding(false);
  336. xwSettings.OmitXmlDeclaration = false;
  337. using (var xw = XmlWriter.Create(ms, xwSettings))
  338. {
  339. var serializer = new DataContractSerializer(from.GetType());
  340. serializer.WriteObject(xw, from);
  341. xw.Flush();
  342. ms.Seek(0, SeekOrigin.Begin);
  343. using (var reader = new StreamReader(ms))
  344. {
  345. return reader.ReadToEnd();
  346. }
  347. }
  348. }
  349. }
  350. /// <summary>
  351. /// Pres the process optimized result.
  352. /// </summary>
  353. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options)
  354. {
  355. bool noCache = requestContext.Headers[HeaderNames.CacheControl].ToString().IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
  356. AddCachingHeaders(responseHeaders, options.CacheDuration, noCache, options.DateLastModified);
  357. if (!noCache)
  358. {
  359. if (!DateTime.TryParseExact(requestContext.Headers[HeaderNames.IfModifiedSince], HttpDateFormat, _enUSculture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var ifModifiedSinceHeader))
  360. {
  361. _logger.LogDebug("Failed to parse If-Modified-Since header date: {0}", requestContext.Headers[HeaderNames.IfModifiedSince]);
  362. return null;
  363. }
  364. if (IsNotModified(ifModifiedSinceHeader, options.CacheDuration, options.DateLastModified))
  365. {
  366. AddAgeHeader(responseHeaders, options.DateLastModified);
  367. var result = new HttpResult(Array.Empty<byte>(), options.ContentType ?? "text/html", HttpStatusCode.NotModified);
  368. AddResponseHeaders(result, responseHeaders);
  369. return result;
  370. }
  371. }
  372. return null;
  373. }
  374. public Task<object> GetStaticFileResult(IRequest requestContext,
  375. string path,
  376. FileShare fileShare = FileShare.Read)
  377. {
  378. if (string.IsNullOrEmpty(path))
  379. {
  380. throw new ArgumentNullException(nameof(path));
  381. }
  382. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  383. {
  384. Path = path,
  385. FileShare = fileShare
  386. });
  387. }
  388. public Task<object> GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options)
  389. {
  390. var path = options.Path;
  391. var fileShare = options.FileShare;
  392. if (string.IsNullOrEmpty(path))
  393. {
  394. throw new ArgumentException("Path can't be empty.", nameof(options));
  395. }
  396. if (fileShare != FileShare.Read && fileShare != FileShare.ReadWrite)
  397. {
  398. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  399. }
  400. if (string.IsNullOrEmpty(options.ContentType))
  401. {
  402. options.ContentType = MimeTypes.GetMimeType(path);
  403. }
  404. if (!options.DateLastModified.HasValue)
  405. {
  406. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  407. }
  408. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  409. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  410. return GetStaticResult(requestContext, options);
  411. }
  412. /// <summary>
  413. /// Gets the file stream.
  414. /// </summary>
  415. /// <param name="path">The path.</param>
  416. /// <param name="fileShare">The file share.</param>
  417. /// <returns>Stream.</returns>
  418. private Stream GetFileStream(string path, FileShare fileShare)
  419. {
  420. return new FileStream(path, FileMode.Open, FileAccess.Read, fileShare);
  421. }
  422. public Task<object> GetStaticResult(IRequest requestContext,
  423. Guid cacheKey,
  424. DateTime? lastDateModified,
  425. TimeSpan? cacheDuration,
  426. string contentType,
  427. Func<Task<Stream>> factoryFn,
  428. IDictionary<string, string> responseHeaders = null,
  429. bool isHeadRequest = false)
  430. {
  431. return GetStaticResult(requestContext, new StaticResultOptions
  432. {
  433. CacheDuration = cacheDuration,
  434. ContentFactory = factoryFn,
  435. ContentType = contentType,
  436. DateLastModified = lastDateModified,
  437. IsHeadRequest = isHeadRequest,
  438. ResponseHeaders = responseHeaders
  439. });
  440. }
  441. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  442. {
  443. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  444. var contentType = options.ContentType;
  445. if (!StringValues.IsNullOrEmpty(requestContext.Headers[HeaderNames.IfModifiedSince]))
  446. {
  447. // See if the result is already cached in the browser
  448. var result = GetCachedResult(requestContext, options.ResponseHeaders, options);
  449. if (result != null)
  450. {
  451. return result;
  452. }
  453. }
  454. // TODO: We don't really need the option value
  455. var isHeadRequest = options.IsHeadRequest || string.Equals(requestContext.Verb, "HEAD", StringComparison.OrdinalIgnoreCase);
  456. var factoryFn = options.ContentFactory;
  457. var responseHeaders = options.ResponseHeaders;
  458. AddCachingHeaders(responseHeaders, options.CacheDuration, false, options.DateLastModified);
  459. AddAgeHeader(responseHeaders, options.DateLastModified);
  460. var rangeHeader = requestContext.Headers[HeaderNames.Range];
  461. if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
  462. {
  463. var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem, _streamHelper)
  464. {
  465. OnComplete = options.OnComplete,
  466. OnError = options.OnError,
  467. FileShare = options.FileShare
  468. };
  469. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  470. return hasHeaders;
  471. }
  472. var stream = await factoryFn().ConfigureAwait(false);
  473. var totalContentLength = options.ContentLength;
  474. if (!totalContentLength.HasValue)
  475. {
  476. try
  477. {
  478. totalContentLength = stream.Length;
  479. }
  480. catch (NotSupportedException)
  481. {
  482. }
  483. }
  484. if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue)
  485. {
  486. var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest)
  487. {
  488. OnComplete = options.OnComplete
  489. };
  490. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  491. return hasHeaders;
  492. }
  493. else
  494. {
  495. if (totalContentLength.HasValue)
  496. {
  497. responseHeaders["Content-Length"] = totalContentLength.Value.ToString(CultureInfo.InvariantCulture);
  498. }
  499. if (isHeadRequest)
  500. {
  501. using (stream)
  502. {
  503. return GetHttpResult(requestContext, Array.Empty<byte>(), contentType, true, responseHeaders);
  504. }
  505. }
  506. var hasHeaders = new StreamWriter(stream, contentType)
  507. {
  508. OnComplete = options.OnComplete,
  509. OnError = options.OnError
  510. };
  511. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  512. return hasHeaders;
  513. }
  514. }
  515. /// <summary>
  516. /// Adds the caching responseHeaders.
  517. /// </summary>
  518. private void AddCachingHeaders(
  519. IDictionary<string, string> responseHeaders,
  520. TimeSpan? cacheDuration,
  521. bool noCache,
  522. DateTime? lastModifiedDate)
  523. {
  524. if (noCache)
  525. {
  526. responseHeaders[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";
  527. responseHeaders[HeaderNames.Pragma] = "no-cache, no-store, must-revalidate";
  528. return;
  529. }
  530. if (cacheDuration.HasValue)
  531. {
  532. responseHeaders[HeaderNames.CacheControl] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
  533. }
  534. else
  535. {
  536. responseHeaders[HeaderNames.CacheControl] = "public";
  537. }
  538. if (lastModifiedDate.HasValue)
  539. {
  540. responseHeaders[HeaderNames.LastModified] = lastModifiedDate.Value.ToUniversalTime().ToString(HttpDateFormat, _enUSculture);
  541. }
  542. }
  543. /// <summary>
  544. /// Adds the age header.
  545. /// </summary>
  546. /// <param name="responseHeaders">The responseHeaders.</param>
  547. /// <param name="lastDateModified">The last date modified.</param>
  548. private static void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  549. {
  550. if (lastDateModified.HasValue)
  551. {
  552. responseHeaders[HeaderNames.Age] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  553. }
  554. }
  555. /// <summary>
  556. /// Determines whether [is not modified] [the specified if modified since].
  557. /// </summary>
  558. /// <param name="ifModifiedSince">If modified since.</param>
  559. /// <param name="cacheDuration">Duration of the cache.</param>
  560. /// <param name="dateModified">The date modified.</param>
  561. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  562. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  563. {
  564. if (dateModified.HasValue)
  565. {
  566. var lastModified = NormalizeDateForComparison(dateModified.Value);
  567. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  568. return lastModified <= ifModifiedSince;
  569. }
  570. if (cacheDuration.HasValue)
  571. {
  572. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  573. if (DateTime.UtcNow < cacheExpirationDate)
  574. {
  575. return true;
  576. }
  577. }
  578. return false;
  579. }
  580. /// <summary>
  581. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that.
  582. /// </summary>
  583. /// <param name="date">The date.</param>
  584. /// <returns>DateTime.</returns>
  585. private static DateTime NormalizeDateForComparison(DateTime date)
  586. {
  587. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  588. }
  589. /// <summary>
  590. /// Adds the response headers.
  591. /// </summary>
  592. /// <param name="hasHeaders">The has options.</param>
  593. /// <param name="responseHeaders">The response headers.</param>
  594. private static void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  595. {
  596. foreach (var item in responseHeaders)
  597. {
  598. hasHeaders.Headers[item.Key] = item.Value;
  599. }
  600. }
  601. }
  602. }