HttpResultFactory.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Model.Logging;
  5. using ServiceStack.Common;
  6. using ServiceStack.Common.Web;
  7. using ServiceStack.ServiceHost;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Net;
  13. using System.Threading.Tasks;
  14. using MimeTypes = MediaBrowser.Common.Net.MimeTypes;
  15. namespace MediaBrowser.Server.Implementations.HttpServer
  16. {
  17. /// <summary>
  18. /// Class HttpResultFactory
  19. /// </summary>
  20. public class HttpResultFactory : IHttpResultFactory
  21. {
  22. /// <summary>
  23. /// The _logger
  24. /// </summary>
  25. private readonly ILogger _logger;
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="HttpResultFactory"/> class.
  28. /// </summary>
  29. /// <param name="logManager">The log manager.</param>
  30. public HttpResultFactory(ILogManager logManager)
  31. {
  32. _logger = logManager.GetLogger("HttpResultFactory");
  33. }
  34. /// <summary>
  35. /// Gets the result.
  36. /// </summary>
  37. /// <param name="content">The content.</param>
  38. /// <param name="contentType">Type of the content.</param>
  39. /// <param name="responseHeaders">The response headers.</param>
  40. /// <returns>System.Object.</returns>
  41. public object GetResult(object content, string contentType, IDictionary<string, string> responseHeaders = null)
  42. {
  43. return GetHttpResult(content, contentType, responseHeaders);
  44. }
  45. /// <summary>
  46. /// Gets the HTTP result.
  47. /// </summary>
  48. /// <param name="content">The content.</param>
  49. /// <param name="contentType">Type of the content.</param>
  50. /// <param name="responseHeaders">The response headers.</param>
  51. /// <returns>IHasOptions.</returns>
  52. private IHasOptions GetHttpResult(object content, string contentType, IDictionary<string, string> responseHeaders = null)
  53. {
  54. IHasOptions result;
  55. var stream = content as Stream;
  56. if (stream != null)
  57. {
  58. result = new StreamWriter(stream, contentType, _logger);
  59. }
  60. else
  61. {
  62. var bytes = content as byte[];
  63. if (bytes != null)
  64. {
  65. result = new StreamWriter(bytes, contentType, _logger);
  66. }
  67. else
  68. {
  69. result = new HttpResult(content, contentType);
  70. }
  71. }
  72. if (responseHeaders != null)
  73. {
  74. AddResponseHeaders(result, responseHeaders);
  75. }
  76. return result;
  77. }
  78. /// <summary>
  79. /// Gets the optimized result.
  80. /// </summary>
  81. /// <typeparam name="T"></typeparam>
  82. /// <param name="requestContext">The request context.</param>
  83. /// <param name="result">The result.</param>
  84. /// <param name="responseHeaders">The response headers.</param>
  85. /// <returns>System.Object.</returns>
  86. /// <exception cref="System.ArgumentNullException">result</exception>
  87. public object GetOptimizedResult<T>(IRequestContext requestContext, T result, IDictionary<string, string> responseHeaders = null)
  88. where T : class
  89. {
  90. if (result == null)
  91. {
  92. throw new ArgumentNullException("result");
  93. }
  94. var optimizedResult = requestContext.ToOptimizedResult(result);
  95. if (responseHeaders != null)
  96. {
  97. // Apply headers
  98. var hasOptions = optimizedResult as IHasOptions;
  99. if (hasOptions != null)
  100. {
  101. AddResponseHeaders(hasOptions, responseHeaders);
  102. }
  103. }
  104. return optimizedResult;
  105. }
  106. /// <summary>
  107. /// Gets the optimized result using cache.
  108. /// </summary>
  109. /// <typeparam name="T"></typeparam>
  110. /// <param name="requestContext">The request context.</param>
  111. /// <param name="cacheKey">The cache key.</param>
  112. /// <param name="lastDateModified">The last date modified.</param>
  113. /// <param name="cacheDuration">Duration of the cache.</param>
  114. /// <param name="factoryFn">The factory fn.</param>
  115. /// <param name="responseHeaders">The response headers.</param>
  116. /// <returns>System.Object.</returns>
  117. /// <exception cref="System.ArgumentNullException">
  118. /// cacheKey
  119. /// or
  120. /// factoryFn
  121. /// </exception>
  122. public object GetOptimizedResultUsingCache<T>(IRequestContext requestContext, Guid cacheKey, DateTime lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, IDictionary<string, string> responseHeaders = null)
  123. where T : class
  124. {
  125. if (cacheKey == Guid.Empty)
  126. {
  127. throw new ArgumentNullException("cacheKey");
  128. }
  129. if (factoryFn == null)
  130. {
  131. throw new ArgumentNullException("factoryFn");
  132. }
  133. var key = cacheKey.ToString("N");
  134. if (responseHeaders == null)
  135. {
  136. responseHeaders = new Dictionary<string, string>();
  137. }
  138. // See if the result is already cached in the browser
  139. var result = GetCachedResult(requestContext, responseHeaders, cacheKey, key, lastDateModified, cacheDuration, null);
  140. if (result != null)
  141. {
  142. return result;
  143. }
  144. return GetOptimizedResult(requestContext, factoryFn(), responseHeaders);
  145. }
  146. /// <summary>
  147. /// To the cached result.
  148. /// </summary>
  149. /// <typeparam name="T"></typeparam>
  150. /// <param name="requestContext">The request context.</param>
  151. /// <param name="cacheKey">The cache key.</param>
  152. /// <param name="lastDateModified">The last date modified.</param>
  153. /// <param name="cacheDuration">Duration of the cache.</param>
  154. /// <param name="factoryFn">The factory fn.</param>
  155. /// <param name="contentType">Type of the content.</param>
  156. /// <param name="responseHeaders">The response headers.</param>
  157. /// <returns>System.Object.</returns>
  158. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  159. public object GetCachedResult<T>(IRequestContext requestContext, Guid cacheKey, DateTime lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, string contentType, IDictionary<string, string> responseHeaders = null)
  160. where T : class
  161. {
  162. if (cacheKey == Guid.Empty)
  163. {
  164. throw new ArgumentNullException("cacheKey");
  165. }
  166. if (factoryFn == null)
  167. {
  168. throw new ArgumentNullException("factoryFn");
  169. }
  170. var key = cacheKey.ToString("N");
  171. if (responseHeaders == null)
  172. {
  173. responseHeaders = new Dictionary<string, string>();
  174. }
  175. // See if the result is already cached in the browser
  176. var result = GetCachedResult(requestContext, responseHeaders, cacheKey, key, lastDateModified, cacheDuration, contentType);
  177. if (result != null)
  178. {
  179. return result;
  180. }
  181. result = factoryFn();
  182. // Apply caching headers
  183. var hasOptions = result as IHasOptions;
  184. if (hasOptions != null)
  185. {
  186. AddResponseHeaders(hasOptions, responseHeaders);
  187. return hasOptions;
  188. }
  189. // Otherwise wrap into an HttpResult
  190. var httpResult = new HttpResult(result, contentType ?? "text/html", HttpStatusCode.NotModified);
  191. AddResponseHeaders(httpResult, responseHeaders);
  192. return httpResult;
  193. }
  194. /// <summary>
  195. /// Pres the process optimized result.
  196. /// </summary>
  197. /// <param name="requestContext">The request context.</param>
  198. /// <param name="responseHeaders">The responseHeaders.</param>
  199. /// <param name="cacheKey">The cache key.</param>
  200. /// <param name="cacheKeyString">The cache key string.</param>
  201. /// <param name="lastDateModified">The last date modified.</param>
  202. /// <param name="cacheDuration">Duration of the cache.</param>
  203. /// <param name="contentType">Type of the content.</param>
  204. /// <returns>System.Object.</returns>
  205. private object GetCachedResult(IRequestContext requestContext, IDictionary<string, string> responseHeaders, Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  206. {
  207. responseHeaders["ETag"] = cacheKeyString;
  208. if (IsNotModified(requestContext, cacheKey, lastDateModified, cacheDuration))
  209. {
  210. AddAgeHeader(responseHeaders, lastDateModified);
  211. AddExpiresHeader(responseHeaders, cacheKeyString, cacheDuration);
  212. var result = new HttpResult(new byte[] { }, contentType ?? "text/html", HttpStatusCode.NotModified);
  213. AddResponseHeaders(result, responseHeaders);
  214. return result;
  215. }
  216. AddCachingHeaders(responseHeaders, cacheKeyString, lastDateModified, cacheDuration);
  217. return null;
  218. }
  219. /// <summary>
  220. /// Gets the static file result.
  221. /// </summary>
  222. /// <param name="requestContext">The request context.</param>
  223. /// <param name="path">The path.</param>
  224. /// <param name="responseHeaders">The response headers.</param>
  225. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  226. /// <returns>System.Object.</returns>
  227. /// <exception cref="System.ArgumentNullException">path</exception>
  228. public object GetStaticFileResult(IRequestContext requestContext, string path, IDictionary<string, string> responseHeaders = null, bool isHeadRequest = false)
  229. {
  230. if (string.IsNullOrEmpty(path))
  231. {
  232. throw new ArgumentNullException("path");
  233. }
  234. var dateModified = File.GetLastWriteTimeUtc(path);
  235. var cacheKey = path + dateModified.Ticks;
  236. return GetStaticResult(requestContext, cacheKey.GetMD5(), dateModified, null, MimeTypes.GetMimeType(path), () => Task.FromResult(GetFileStream(path)), responseHeaders, isHeadRequest);
  237. }
  238. /// <summary>
  239. /// Gets the file stream.
  240. /// </summary>
  241. /// <param name="path">The path.</param>
  242. /// <returns>Stream.</returns>
  243. private Stream GetFileStream(string path)
  244. {
  245. return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  246. }
  247. /// <summary>
  248. /// Gets the static result.
  249. /// </summary>
  250. /// <param name="requestContext">The request context.</param>
  251. /// <param name="cacheKey">The cache key.</param>
  252. /// <param name="lastDateModified">The last date modified.</param>
  253. /// <param name="cacheDuration">Duration of the cache.</param>
  254. /// <param name="contentType">Type of the content.</param>
  255. /// <param name="factoryFn">The factory fn.</param>
  256. /// <param name="responseHeaders">The response headers.</param>
  257. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  258. /// <returns>System.Object.</returns>
  259. /// <exception cref="System.ArgumentNullException">cacheKey
  260. /// or
  261. /// factoryFn</exception>
  262. public object GetStaticResult(IRequestContext requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType, Func<Task<Stream>> factoryFn, IDictionary<string, string> responseHeaders = null, bool isHeadRequest = false)
  263. {
  264. if (cacheKey == Guid.Empty)
  265. {
  266. throw new ArgumentNullException("cacheKey");
  267. }
  268. if (factoryFn == null)
  269. {
  270. throw new ArgumentNullException("factoryFn");
  271. }
  272. var key = cacheKey.ToString("N");
  273. if (responseHeaders == null)
  274. {
  275. responseHeaders = new Dictionary<string, string>();
  276. }
  277. // See if the result is already cached in the browser
  278. var result = GetCachedResult(requestContext, responseHeaders, cacheKey, key, lastDateModified, cacheDuration, contentType);
  279. if (result != null)
  280. {
  281. return result;
  282. }
  283. var compress = ShouldCompressResponse(requestContext, contentType);
  284. var hasOptions = GetStaticResult(requestContext, responseHeaders, contentType, factoryFn, compress, isHeadRequest).Result;
  285. AddResponseHeaders(hasOptions, responseHeaders);
  286. return hasOptions;
  287. }
  288. /// <summary>
  289. /// Shoulds the compress response.
  290. /// </summary>
  291. /// <param name="requestContext">The request context.</param>
  292. /// <param name="contentType">Type of the content.</param>
  293. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  294. private bool ShouldCompressResponse(IRequestContext requestContext, string contentType)
  295. {
  296. // It will take some work to support compression with byte range requests
  297. if (!string.IsNullOrEmpty(requestContext.GetHeader("Range")))
  298. {
  299. return false;
  300. }
  301. // Don't compress media
  302. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  303. {
  304. return false;
  305. }
  306. // Don't compress images
  307. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  308. {
  309. return false;
  310. }
  311. if (contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  312. {
  313. return false;
  314. }
  315. if (contentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase))
  316. {
  317. return false;
  318. }
  319. return true;
  320. }
  321. /// <summary>
  322. /// The us culture
  323. /// </summary>
  324. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  325. /// <summary>
  326. /// Gets the static result.
  327. /// </summary>
  328. /// <param name="requestContext">The request context.</param>
  329. /// <param name="responseHeaders">The response headers.</param>
  330. /// <param name="contentType">Type of the content.</param>
  331. /// <param name="factoryFn">The factory fn.</param>
  332. /// <param name="compress">if set to <c>true</c> [compress].</param>
  333. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  334. /// <returns>Task{IHasOptions}.</returns>
  335. private async Task<IHasOptions> GetStaticResult(IRequestContext requestContext, IDictionary<string, string> responseHeaders, string contentType, Func<Task<Stream>> factoryFn, bool compress, bool isHeadRequest)
  336. {
  337. if (!compress || string.IsNullOrEmpty(requestContext.CompressionType))
  338. {
  339. var stream = await factoryFn().ConfigureAwait(false);
  340. var rangeHeader = requestContext.GetHeader("Range");
  341. if (!string.IsNullOrEmpty(rangeHeader))
  342. {
  343. return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest);
  344. }
  345. responseHeaders["Content-Length"] = stream.Length.ToString(UsCulture);
  346. if (isHeadRequest)
  347. {
  348. return GetHttpResult(new byte[] { }, contentType);
  349. }
  350. return new StreamWriter(stream, contentType, _logger);
  351. }
  352. if (isHeadRequest)
  353. {
  354. return GetHttpResult(new byte[] { }, contentType);
  355. }
  356. string content;
  357. using (var stream = await factoryFn().ConfigureAwait(false))
  358. {
  359. using (var reader = new StreamReader(stream))
  360. {
  361. content = await reader.ReadToEndAsync().ConfigureAwait(false);
  362. }
  363. }
  364. var contents = content.Compress(requestContext.CompressionType);
  365. return new CompressedResult(contents, requestContext.CompressionType, contentType);
  366. }
  367. /// <summary>
  368. /// Adds the caching responseHeaders.
  369. /// </summary>
  370. /// <param name="responseHeaders">The responseHeaders.</param>
  371. /// <param name="cacheKey">The cache key.</param>
  372. /// <param name="lastDateModified">The last date modified.</param>
  373. /// <param name="cacheDuration">Duration of the cache.</param>
  374. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  375. {
  376. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  377. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  378. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  379. {
  380. AddAgeHeader(responseHeaders, lastDateModified);
  381. responseHeaders["LastModified"] = lastDateModified.Value.ToString("r");
  382. }
  383. if (cacheDuration.HasValue)
  384. {
  385. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  386. }
  387. else if (!string.IsNullOrEmpty(cacheKey))
  388. {
  389. responseHeaders["Cache-Control"] = "public";
  390. }
  391. else
  392. {
  393. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  394. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  395. }
  396. AddExpiresHeader(responseHeaders, cacheKey, cacheDuration);
  397. }
  398. /// <summary>
  399. /// Adds the expires header.
  400. /// </summary>
  401. /// <param name="responseHeaders">The responseHeaders.</param>
  402. /// <param name="cacheKey">The cache key.</param>
  403. /// <param name="cacheDuration">Duration of the cache.</param>
  404. private void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration)
  405. {
  406. if (cacheDuration.HasValue)
  407. {
  408. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  409. }
  410. else if (string.IsNullOrEmpty(cacheKey))
  411. {
  412. responseHeaders["Expires"] = "-1";
  413. }
  414. }
  415. /// <summary>
  416. /// Adds the age header.
  417. /// </summary>
  418. /// <param name="responseHeaders">The responseHeaders.</param>
  419. /// <param name="lastDateModified">The last date modified.</param>
  420. private void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  421. {
  422. if (lastDateModified.HasValue)
  423. {
  424. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  425. }
  426. }
  427. /// <summary>
  428. /// Determines whether [is not modified] [the specified cache key].
  429. /// </summary>
  430. /// <param name="requestContext">The request context.</param>
  431. /// <param name="cacheKey">The cache key.</param>
  432. /// <param name="lastDateModified">The last date modified.</param>
  433. /// <param name="cacheDuration">Duration of the cache.</param>
  434. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  435. private bool IsNotModified(IRequestContext requestContext, Guid? cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  436. {
  437. var isNotModified = true;
  438. var ifModifiedSinceHeader = requestContext.GetHeader("If-Modified-Since");
  439. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  440. {
  441. DateTime ifModifiedSince;
  442. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  443. {
  444. isNotModified = IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified);
  445. }
  446. }
  447. var ifNoneMatchHeader = requestContext.GetHeader("If-None-Match");
  448. // Validate If-None-Match
  449. if (isNotModified && (cacheKey.HasValue || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  450. {
  451. Guid ifNoneMatch;
  452. if (Guid.TryParse(ifNoneMatchHeader ?? string.Empty, out ifNoneMatch))
  453. {
  454. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  455. {
  456. return true;
  457. }
  458. }
  459. }
  460. return false;
  461. }
  462. /// <summary>
  463. /// Determines whether [is not modified] [the specified if modified since].
  464. /// </summary>
  465. /// <param name="ifModifiedSince">If modified since.</param>
  466. /// <param name="cacheDuration">Duration of the cache.</param>
  467. /// <param name="dateModified">The date modified.</param>
  468. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  469. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  470. {
  471. if (dateModified.HasValue)
  472. {
  473. var lastModified = NormalizeDateForComparison(dateModified.Value);
  474. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  475. return lastModified <= ifModifiedSince;
  476. }
  477. if (cacheDuration.HasValue)
  478. {
  479. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  480. if (DateTime.UtcNow < cacheExpirationDate)
  481. {
  482. return true;
  483. }
  484. }
  485. return false;
  486. }
  487. /// <summary>
  488. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  489. /// </summary>
  490. /// <param name="date">The date.</param>
  491. /// <returns>DateTime.</returns>
  492. private DateTime NormalizeDateForComparison(DateTime date)
  493. {
  494. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  495. }
  496. /// <summary>
  497. /// Adds the response headers.
  498. /// </summary>
  499. /// <param name="hasOptions">The has options.</param>
  500. /// <param name="responseHeaders">The response headers.</param>
  501. private void AddResponseHeaders(IHasOptions hasOptions, IDictionary<string, string> responseHeaders)
  502. {
  503. foreach (var item in responseHeaders)
  504. {
  505. hasOptions.Options[item.Key] = item.Value;
  506. }
  507. }
  508. /// <summary>
  509. /// Gets the error result.
  510. /// </summary>
  511. /// <param name="statusCode">The status code.</param>
  512. /// <param name="errorMessage">The error message.</param>
  513. /// <param name="responseHeaders">The response headers.</param>
  514. /// <returns>System.Object.</returns>
  515. public void ThrowError(int statusCode, string errorMessage, IDictionary<string, string> responseHeaders = null)
  516. {
  517. var error = new HttpError
  518. {
  519. Status = statusCode,
  520. ErrorCode = errorMessage
  521. };
  522. if (responseHeaders != null)
  523. {
  524. AddResponseHeaders(error, responseHeaders);
  525. }
  526. throw error;
  527. }
  528. }
  529. }