BaseApiService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Session;
  6. using MediaBrowser.Model.Logging;
  7. using ServiceStack.Common.Web;
  8. using ServiceStack.ServiceHost;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Api
  14. {
  15. /// <summary>
  16. /// Class BaseApiService
  17. /// </summary>
  18. [RequestFilter]
  19. public class BaseApiService : IHasResultFactory, IRestfulService
  20. {
  21. /// <summary>
  22. /// Gets or sets the logger.
  23. /// </summary>
  24. /// <value>The logger.</value>
  25. public ILogger Logger { get; set; }
  26. /// <summary>
  27. /// Gets or sets the HTTP result factory.
  28. /// </summary>
  29. /// <value>The HTTP result factory.</value>
  30. public IHttpResultFactory ResultFactory { get; set; }
  31. /// <summary>
  32. /// Gets or sets the request context.
  33. /// </summary>
  34. /// <value>The request context.</value>
  35. public IRequestContext RequestContext { get; set; }
  36. /// <summary>
  37. /// To the optimized result.
  38. /// </summary>
  39. /// <typeparam name="T"></typeparam>
  40. /// <param name="result">The result.</param>
  41. /// <returns>System.Object.</returns>
  42. protected object ToOptimizedResult<T>(T result)
  43. where T : class
  44. {
  45. return ResultFactory.GetOptimizedResult(RequestContext, result);
  46. }
  47. /// <summary>
  48. /// To the optimized result using cache.
  49. /// </summary>
  50. /// <typeparam name="T"></typeparam>
  51. /// <param name="cacheKey">The cache key.</param>
  52. /// <param name="lastDateModified">The last date modified.</param>
  53. /// <param name="cacheDuration">Duration of the cache.</param>
  54. /// <param name="factoryFn">The factory fn.</param>
  55. /// <returns>System.Object.</returns>
  56. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  57. protected object ToOptimizedResultUsingCache<T>(Guid cacheKey, DateTime lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn)
  58. where T : class
  59. {
  60. return ResultFactory.GetOptimizedResultUsingCache(RequestContext, cacheKey, lastDateModified, cacheDuration, factoryFn);
  61. }
  62. /// <summary>
  63. /// To the cached result.
  64. /// </summary>
  65. /// <typeparam name="T"></typeparam>
  66. /// <param name="cacheKey">The cache key.</param>
  67. /// <param name="lastDateModified">The last date modified.</param>
  68. /// <param name="cacheDuration">Duration of the cache.</param>
  69. /// <param name="factoryFn">The factory fn.</param>
  70. /// <param name="contentType">Type of the content.</param>
  71. /// <returns>System.Object.</returns>
  72. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  73. protected object ToCachedResult<T>(Guid cacheKey, DateTime lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, string contentType)
  74. where T : class
  75. {
  76. return ResultFactory.GetCachedResult(RequestContext, cacheKey, lastDateModified, cacheDuration, factoryFn, contentType);
  77. }
  78. /// <summary>
  79. /// To the static file result.
  80. /// </summary>
  81. /// <param name="path">The path.</param>
  82. /// <returns>System.Object.</returns>
  83. protected object ToStaticFileResult(string path)
  84. {
  85. return ResultFactory.GetStaticFileResult(RequestContext, path);
  86. }
  87. private readonly char[] _dashReplaceChars = new[] { '?', '/' };
  88. private const char SlugChar = '-';
  89. protected Task<Artist> GetArtist(string name, ILibraryManager libraryManager)
  90. {
  91. return libraryManager.GetArtist(DeSlugArtistName(name, libraryManager));
  92. }
  93. protected Task<Studio> GetStudio(string name, ILibraryManager libraryManager)
  94. {
  95. return libraryManager.GetStudio(DeSlugStudioName(name, libraryManager));
  96. }
  97. protected Task<Genre> GetGenre(string name, ILibraryManager libraryManager)
  98. {
  99. return libraryManager.GetGenre(DeSlugGenreName(name, libraryManager));
  100. }
  101. protected Task<Person> GetPerson(string name, ILibraryManager libraryManager)
  102. {
  103. return libraryManager.GetPerson(DeSlugPersonName(name, libraryManager));
  104. }
  105. /// <summary>
  106. /// Deslugs an artist name by finding the correct entry in the library
  107. /// </summary>
  108. /// <param name="name"></param>
  109. /// <param name="libraryManager"></param>
  110. /// <returns></returns>
  111. protected string DeSlugArtistName(string name, ILibraryManager libraryManager)
  112. {
  113. if (name.IndexOf(SlugChar) == -1)
  114. {
  115. return name;
  116. }
  117. return libraryManager.RootFolder.RecursiveChildren
  118. .OfType<Audio>()
  119. .SelectMany(i => new[] { i.Artist, i.AlbumArtist })
  120. .Where(i => !string.IsNullOrEmpty(i))
  121. .Distinct(StringComparer.OrdinalIgnoreCase)
  122. .FirstOrDefault(i =>
  123. {
  124. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  125. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  126. }) ?? name;
  127. }
  128. /// <summary>
  129. /// Deslugs a genre name by finding the correct entry in the library
  130. /// </summary>
  131. protected string DeSlugGenreName(string name, ILibraryManager libraryManager)
  132. {
  133. if (name.IndexOf(SlugChar) == -1)
  134. {
  135. return name;
  136. }
  137. return libraryManager.RootFolder.RecursiveChildren
  138. .SelectMany(i => i.Genres)
  139. .Distinct(StringComparer.OrdinalIgnoreCase)
  140. .FirstOrDefault(i =>
  141. {
  142. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  143. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  144. }) ?? name;
  145. }
  146. /// <summary>
  147. /// Deslugs a studio name by finding the correct entry in the library
  148. /// </summary>
  149. protected string DeSlugStudioName(string name, ILibraryManager libraryManager)
  150. {
  151. if (name.IndexOf(SlugChar) == -1)
  152. {
  153. return name;
  154. }
  155. return libraryManager.RootFolder.RecursiveChildren
  156. .SelectMany(i => i.Studios)
  157. .Distinct(StringComparer.OrdinalIgnoreCase)
  158. .FirstOrDefault(i =>
  159. {
  160. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  161. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  162. }) ?? name;
  163. }
  164. /// <summary>
  165. /// Deslugs a person name by finding the correct entry in the library
  166. /// </summary>
  167. protected string DeSlugPersonName(string name, ILibraryManager libraryManager)
  168. {
  169. if (name.IndexOf(SlugChar) == -1)
  170. {
  171. return name;
  172. }
  173. return libraryManager.RootFolder.RecursiveChildren
  174. .SelectMany(i => i.People)
  175. .Select(i => i.Name)
  176. .Distinct(StringComparer.OrdinalIgnoreCase)
  177. .FirstOrDefault(i =>
  178. {
  179. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  180. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  181. }) ?? name;
  182. }
  183. }
  184. /// <summary>
  185. /// Class RequestFilterAttribute
  186. /// </summary>
  187. public class RequestFilterAttribute : Attribute, IHasRequestFilter
  188. {
  189. //This property will be resolved by the IoC container
  190. /// <summary>
  191. /// Gets or sets the user manager.
  192. /// </summary>
  193. /// <value>The user manager.</value>
  194. public IUserManager UserManager { get; set; }
  195. public ISessionManager SessionManager { get; set; }
  196. /// <summary>
  197. /// Gets or sets the logger.
  198. /// </summary>
  199. /// <value>The logger.</value>
  200. public ILogger Logger { get; set; }
  201. /// <summary>
  202. /// The request filter is executed before the service.
  203. /// </summary>
  204. /// <param name="request">The http request wrapper</param>
  205. /// <param name="response">The http response wrapper</param>
  206. /// <param name="requestDto">The request DTO</param>
  207. public void RequestFilter(IHttpRequest request, IHttpResponse response, object requestDto)
  208. {
  209. //This code is executed before the service
  210. var auth = GetAuthorization(request);
  211. if (auth != null)
  212. {
  213. User user = null;
  214. if (auth.ContainsKey("UserId"))
  215. {
  216. var userId = auth["UserId"];
  217. if (!string.IsNullOrEmpty(userId))
  218. {
  219. user = UserManager.GetUserById(new Guid(userId));
  220. }
  221. }
  222. var deviceId = auth["DeviceId"];
  223. var device = auth["Device"];
  224. var client = auth["Client"];
  225. if (!string.IsNullOrEmpty(client) && !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(device))
  226. {
  227. SessionManager.LogConnectionActivity(client, deviceId, device, user);
  228. }
  229. }
  230. }
  231. /// <summary>
  232. /// Gets the auth.
  233. /// </summary>
  234. /// <param name="httpReq">The HTTP req.</param>
  235. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  236. public static Dictionary<string, string> GetAuthorization(IHttpRequest httpReq)
  237. {
  238. var auth = httpReq.Headers[HttpHeaders.Authorization];
  239. return GetAuthorization(auth);
  240. }
  241. /// <summary>
  242. /// Gets the authorization.
  243. /// </summary>
  244. /// <param name="httpReq">The HTTP req.</param>
  245. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  246. public static Dictionary<string, string> GetAuthorization(IRequestContext httpReq)
  247. {
  248. var auth = httpReq.GetHeader("Authorization");
  249. return GetAuthorization(auth);
  250. }
  251. /// <summary>
  252. /// Gets the authorization.
  253. /// </summary>
  254. /// <param name="authorizationHeader">The authorization header.</param>
  255. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  256. private static Dictionary<string, string> GetAuthorization(string authorizationHeader)
  257. {
  258. if (authorizationHeader == null) return null;
  259. var parts = authorizationHeader.Split(' ');
  260. // There should be at least to parts
  261. if (parts.Length < 2) return null;
  262. // It has to be a digest request
  263. if (!string.Equals(parts[0], "MediaBrowser", StringComparison.OrdinalIgnoreCase))
  264. {
  265. return null;
  266. }
  267. // Remove uptil the first space
  268. authorizationHeader = authorizationHeader.Substring(authorizationHeader.IndexOf(' '));
  269. parts = authorizationHeader.Split(',');
  270. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  271. foreach (var item in parts)
  272. {
  273. var param = item.Trim().Split(new[] { '=' }, 2);
  274. result.Add(param[0], param[1].Trim(new[] { '"' }));
  275. }
  276. return result;
  277. }
  278. /// <summary>
  279. /// A new shallow copy of this filter is used on every request.
  280. /// </summary>
  281. /// <returns>IHasRequestFilter.</returns>
  282. public IHasRequestFilter Copy()
  283. {
  284. return this;
  285. }
  286. /// <summary>
  287. /// Order in which Request Filters are executed.
  288. /// &lt;0 Executed before global request filters
  289. /// &gt;0 Executed after global request filters
  290. /// </summary>
  291. /// <value>The priority.</value>
  292. public int Priority
  293. {
  294. get { return 0; }
  295. }
  296. }
  297. }