BaseRestService.cs 17 KB

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