BaseRestService.cs 16 KB

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