BaseRestService.cs 17 KB

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