BaseRestService.cs 17 KB

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