BaseRestService.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. using System.Collections.Generic;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Common.Kernel;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Model.Logging;
  7. using ServiceStack.Common;
  8. using ServiceStack.Common.Web;
  9. using ServiceStack.ServiceHost;
  10. using ServiceStack.ServiceInterface;
  11. using System;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading.Tasks;
  16. using MimeTypes = MediaBrowser.Common.Net.MimeTypes;
  17. namespace MediaBrowser.Common.Implementations.HttpServer
  18. {
  19. /// <summary>
  20. /// Class BaseRestService
  21. /// </summary>
  22. public class BaseRestService : Service, IRestfulService
  23. {
  24. /// <summary>
  25. /// Gets or sets the kernel.
  26. /// </summary>
  27. /// <value>The kernel.</value>
  28. public IKernel Kernel { get; set; }
  29. /// <summary>
  30. /// Gets or sets the logger.
  31. /// </summary>
  32. /// <value>The logger.</value>
  33. public ILogger Logger { get; set; }
  34. /// <summary>
  35. /// Gets a value indicating whether this instance is range request.
  36. /// </summary>
  37. /// <value><c>true</c> if this instance is range request; otherwise, <c>false</c>.</value>
  38. protected bool IsRangeRequest
  39. {
  40. get
  41. {
  42. return Request.Headers.AllKeys.Contains("Range");
  43. }
  44. }
  45. /// <summary>
  46. /// To the optimized result.
  47. /// </summary>
  48. /// <typeparam name="T"></typeparam>
  49. /// <param name="result">The result.</param>
  50. /// <returns>System.Object.</returns>
  51. /// <exception cref="System.ArgumentNullException">result</exception>
  52. protected object ToOptimizedResult<T>(T result)
  53. where T : class
  54. {
  55. if (result == null)
  56. {
  57. throw new ArgumentNullException("result");
  58. }
  59. Response.AddHeader("Vary", "Accept-Encoding");
  60. return RequestContext.ToOptimizedResult(result);
  61. }
  62. /// <summary>
  63. /// To the optimized result using cache.
  64. /// </summary>
  65. /// <typeparam name="T"></typeparam>
  66. /// <param name="cacheKey">The cache key.</param>
  67. /// <param name="lastDateModified">The last date modified.</param>
  68. /// <param name="cacheDuration">Duration of the cache.</param>
  69. /// <param name="factoryFn">The factory fn.</param>
  70. /// <returns>System.Object.</returns>
  71. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  72. protected object ToOptimizedResultUsingCache<T>(Guid cacheKey, DateTime lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn)
  73. where T : class
  74. {
  75. if (cacheKey == Guid.Empty)
  76. {
  77. throw new ArgumentNullException("cacheKey");
  78. }
  79. if (factoryFn == null)
  80. {
  81. throw new ArgumentNullException("factoryFn");
  82. }
  83. var key = cacheKey.ToString("N");
  84. var result = PreProcessCachedResult(cacheKey, key, lastDateModified, cacheDuration, string.Empty);
  85. if (result != null)
  86. {
  87. // Return null so that service stack won't do anything
  88. return null;
  89. }
  90. return ToOptimizedResult(factoryFn());
  91. }
  92. /// <summary>
  93. /// To the cached result.
  94. /// </summary>
  95. /// <typeparam name="T"></typeparam>
  96. /// <param name="cacheKey">The cache key.</param>
  97. /// <param name="lastDateModified">The last date modified.</param>
  98. /// <param name="cacheDuration">Duration of the cache.</param>
  99. /// <param name="factoryFn">The factory fn.</param>
  100. /// <param name="contentType">Type of the content.</param>
  101. /// <returns>System.Object.</returns>
  102. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  103. protected object ToCachedResult<T>(Guid cacheKey, DateTime lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, string contentType)
  104. where T : class
  105. {
  106. if (cacheKey == Guid.Empty)
  107. {
  108. throw new ArgumentNullException("cacheKey");
  109. }
  110. if (factoryFn == null)
  111. {
  112. throw new ArgumentNullException("factoryFn");
  113. }
  114. var key = cacheKey.ToString("N");
  115. var result = PreProcessCachedResult(cacheKey, key, lastDateModified, cacheDuration, contentType);
  116. if (result != null)
  117. {
  118. // Return null so that service stack won't do anything
  119. return null;
  120. }
  121. return factoryFn();
  122. }
  123. /// <summary>
  124. /// To the static file result.
  125. /// </summary>
  126. /// <param name="path">The path.</param>
  127. /// <returns>System.Object.</returns>
  128. /// <exception cref="System.ArgumentNullException">path</exception>
  129. protected object ToStaticFileResult(string path)
  130. {
  131. if (string.IsNullOrEmpty(path))
  132. {
  133. throw new ArgumentNullException("path");
  134. }
  135. var dateModified = File.GetLastWriteTimeUtc(path);
  136. var cacheKey = path + dateModified.Ticks;
  137. return ToStaticResult(cacheKey.GetMD5(), dateModified, null, MimeTypes.GetMimeType(path), () => Task.FromResult(GetFileStream(path)));
  138. }
  139. /// <summary>
  140. /// Gets the file stream.
  141. /// </summary>
  142. /// <param name="path">The path.</param>
  143. /// <returns>Stream.</returns>
  144. private Stream GetFileStream(string path)
  145. {
  146. return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  147. }
  148. /// <summary>
  149. /// To the static result.
  150. /// </summary>
  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="contentType">Type of the content.</param>
  155. /// <param name="factoryFn">The factory fn.</param>
  156. /// <returns>System.Object.</returns>
  157. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  158. protected object ToStaticResult(Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType, Func<Task<Stream>> factoryFn)
  159. {
  160. if (cacheKey == Guid.Empty)
  161. {
  162. throw new ArgumentNullException("cacheKey");
  163. }
  164. if (factoryFn == null)
  165. {
  166. throw new ArgumentNullException("factoryFn");
  167. }
  168. var key = cacheKey.ToString("N");
  169. var result = PreProcessCachedResult(cacheKey, key, lastDateModified, cacheDuration, contentType);
  170. if (result != null)
  171. {
  172. // Return null so that service stack won't do anything
  173. return null;
  174. }
  175. var compress = ShouldCompressResponse(contentType);
  176. if (compress)
  177. {
  178. Response.AddHeader("Vary", "Accept-Encoding");
  179. }
  180. return ToStaticResult(contentType, factoryFn, compress).Result;
  181. }
  182. /// <summary>
  183. /// Shoulds the compress response.
  184. /// </summary>
  185. /// <param name="contentType">Type of the content.</param>
  186. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  187. private bool ShouldCompressResponse(string contentType)
  188. {
  189. // It will take some work to support compression with byte range requests
  190. if (IsRangeRequest)
  191. {
  192. return false;
  193. }
  194. // Don't compress media
  195. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  196. {
  197. return false;
  198. }
  199. // Don't compress images
  200. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  201. {
  202. return false;
  203. }
  204. if (contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  205. {
  206. return false;
  207. }
  208. if (contentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase))
  209. {
  210. return false;
  211. }
  212. return true;
  213. }
  214. /// <summary>
  215. /// To the static result.
  216. /// </summary>
  217. /// <param name="contentType">Type of the content.</param>
  218. /// <param name="factoryFn">The factory fn.</param>
  219. /// <param name="compress">if set to <c>true</c> [compress].</param>
  220. /// <returns>System.Object.</returns>
  221. private async Task<object> ToStaticResult(string contentType, Func<Task<Stream>> factoryFn, bool compress)
  222. {
  223. if (!compress || string.IsNullOrEmpty(RequestContext.CompressionType))
  224. {
  225. Response.ContentType = contentType;
  226. var stream = await factoryFn().ConfigureAwait(false);
  227. return new StreamWriter(stream);
  228. }
  229. string content;
  230. using (var stream = await factoryFn().ConfigureAwait(false))
  231. {
  232. using (var reader = new StreamReader(stream))
  233. {
  234. content = await reader.ReadToEndAsync().ConfigureAwait(false);
  235. }
  236. }
  237. var contents = content.Compress(RequestContext.CompressionType);
  238. return new CompressedResult(contents, RequestContext.CompressionType, contentType);
  239. }
  240. /// <summary>
  241. /// Pres the process optimized result.
  242. /// </summary>
  243. /// <param name="cacheKey">The cache key.</param>
  244. /// <param name="cacheKeyString">The cache key string.</param>
  245. /// <param name="lastDateModified">The last date modified.</param>
  246. /// <param name="cacheDuration">Duration of the cache.</param>
  247. /// <param name="contentType">Type of the content.</param>
  248. /// <returns>System.Object.</returns>
  249. private object PreProcessCachedResult(Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  250. {
  251. Response.AddHeader("ETag", cacheKeyString);
  252. if (IsNotModified(cacheKey, lastDateModified, cacheDuration))
  253. {
  254. AddAgeHeader(lastDateModified);
  255. AddExpiresHeader(cacheKeyString, cacheDuration);
  256. //ctx.Response.SendChunked = false;
  257. if (!string.IsNullOrEmpty(contentType))
  258. {
  259. Response.ContentType = contentType;
  260. }
  261. Response.StatusCode = 304;
  262. return new byte[]{};
  263. }
  264. SetCachingHeaders(cacheKeyString, lastDateModified, cacheDuration);
  265. return null;
  266. }
  267. /// <summary>
  268. /// Determines whether [is not modified] [the specified cache key].
  269. /// </summary>
  270. /// <param name="cacheKey">The cache key.</param>
  271. /// <param name="lastDateModified">The last date modified.</param>
  272. /// <param name="cacheDuration">Duration of the cache.</param>
  273. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  274. private bool IsNotModified(Guid? cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  275. {
  276. var isNotModified = true;
  277. if (Request.Headers.AllKeys.Contains("If-Modified-Since"))
  278. {
  279. DateTime ifModifiedSince;
  280. if (DateTime.TryParse(Request.Headers["If-Modified-Since"], out ifModifiedSince))
  281. {
  282. isNotModified = IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified);
  283. }
  284. }
  285. // Validate If-None-Match
  286. if (isNotModified && (cacheKey.HasValue || !string.IsNullOrEmpty(Request.Headers["If-None-Match"])))
  287. {
  288. Guid ifNoneMatch;
  289. if (Guid.TryParse(Request.Headers["If-None-Match"] ?? string.Empty, out ifNoneMatch))
  290. {
  291. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  292. {
  293. return true;
  294. }
  295. }
  296. }
  297. return false;
  298. }
  299. /// <summary>
  300. /// Determines whether [is not modified] [the specified if modified since].
  301. /// </summary>
  302. /// <param name="ifModifiedSince">If modified since.</param>
  303. /// <param name="cacheDuration">Duration of the cache.</param>
  304. /// <param name="dateModified">The date modified.</param>
  305. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  306. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  307. {
  308. if (dateModified.HasValue)
  309. {
  310. var lastModified = NormalizeDateForComparison(dateModified.Value);
  311. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  312. return lastModified <= ifModifiedSince;
  313. }
  314. if (cacheDuration.HasValue)
  315. {
  316. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  317. if (DateTime.UtcNow < cacheExpirationDate)
  318. {
  319. return true;
  320. }
  321. }
  322. return false;
  323. }
  324. /// <summary>
  325. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  326. /// </summary>
  327. /// <param name="date">The date.</param>
  328. /// <returns>DateTime.</returns>
  329. private DateTime NormalizeDateForComparison(DateTime date)
  330. {
  331. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  332. }
  333. /// <summary>
  334. /// Sets the caching headers.
  335. /// </summary>
  336. /// <param name="cacheKey">The cache key.</param>
  337. /// <param name="lastDateModified">The last date modified.</param>
  338. /// <param name="cacheDuration">Duration of the cache.</param>
  339. private void SetCachingHeaders(string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  340. {
  341. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  342. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  343. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  344. {
  345. AddAgeHeader(lastDateModified);
  346. Response.AddHeader("LastModified", lastDateModified.Value.ToString("r"));
  347. }
  348. if (cacheDuration.HasValue)
  349. {
  350. Response.AddHeader("Cache-Control", "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds));
  351. }
  352. else if (!string.IsNullOrEmpty(cacheKey))
  353. {
  354. Response.AddHeader("Cache-Control", "public");
  355. }
  356. else
  357. {
  358. Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  359. Response.AddHeader("pragma", "no-cache, no-store, must-revalidate");
  360. }
  361. AddExpiresHeader(cacheKey, cacheDuration);
  362. }
  363. /// <summary>
  364. /// Adds the expires header.
  365. /// </summary>
  366. /// <param name="cacheKey">The cache key.</param>
  367. /// <param name="cacheDuration">Duration of the cache.</param>
  368. private void AddExpiresHeader(string cacheKey, TimeSpan? cacheDuration)
  369. {
  370. if (cacheDuration.HasValue)
  371. {
  372. Response.AddHeader("Expires", DateTime.UtcNow.Add(cacheDuration.Value).ToString("r"));
  373. }
  374. else if (string.IsNullOrEmpty(cacheKey))
  375. {
  376. Response.AddHeader("Expires", "-1");
  377. }
  378. }
  379. /// <summary>
  380. /// Adds the age header.
  381. /// </summary>
  382. /// <param name="lastDateModified">The last date modified.</param>
  383. private void AddAgeHeader(DateTime? lastDateModified)
  384. {
  385. if (lastDateModified.HasValue)
  386. {
  387. Response.AddHeader("Age", Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture));
  388. }
  389. }
  390. /// <summary>
  391. /// Gets the routes.
  392. /// </summary>
  393. /// <returns>IEnumerable{RouteInfo}.</returns>
  394. public IEnumerable<RouteInfo> GetRoutes()
  395. {
  396. return new RouteInfo[] {};
  397. }
  398. }
  399. }