BaseRestService.cs 17 KB

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