HttpResultFactory.cs 23 KB

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