HttpResultFactory.cs 26 KB

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