HttpResultFactory.cs 26 KB

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