BaseRestService.cs 17 KB

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