BaseApiService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. namespace MediaBrowser.Api
  13. {
  14. /// <summary>
  15. /// Class BaseApiService
  16. /// </summary>
  17. [RequestFilter]
  18. public class BaseApiService : IHasResultFactory, IRestfulService
  19. {
  20. /// <summary>
  21. /// Gets or sets the logger.
  22. /// </summary>
  23. /// <value>The logger.</value>
  24. public ILogger Logger { get; set; }
  25. /// <summary>
  26. /// Gets or sets the HTTP result factory.
  27. /// </summary>
  28. /// <value>The HTTP result factory.</value>
  29. public IHttpResultFactory ResultFactory { get; set; }
  30. /// <summary>
  31. /// Gets or sets the request context.
  32. /// </summary>
  33. /// <value>The request context.</value>
  34. public IRequestContext RequestContext { get; set; }
  35. /// <summary>
  36. /// To the optimized result.
  37. /// </summary>
  38. /// <typeparam name="T"></typeparam>
  39. /// <param name="result">The result.</param>
  40. /// <returns>System.Object.</returns>
  41. protected object ToOptimizedResult<T>(T result)
  42. where T : class
  43. {
  44. return ResultFactory.GetOptimizedResult(RequestContext, result);
  45. }
  46. /// <summary>
  47. /// To the optimized result using cache.
  48. /// </summary>
  49. /// <typeparam name="T"></typeparam>
  50. /// <param name="cacheKey">The cache key.</param>
  51. /// <param name="lastDateModified">The last date modified.</param>
  52. /// <param name="cacheDuration">Duration of the cache.</param>
  53. /// <param name="factoryFn">The factory fn.</param>
  54. /// <returns>System.Object.</returns>
  55. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  56. protected object ToOptimizedResultUsingCache<T>(Guid cacheKey, DateTime lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn)
  57. where T : class
  58. {
  59. return ResultFactory.GetOptimizedResultUsingCache(RequestContext, cacheKey, lastDateModified, cacheDuration, factoryFn);
  60. }
  61. /// <summary>
  62. /// To the cached result.
  63. /// </summary>
  64. /// <typeparam name="T"></typeparam>
  65. /// <param name="cacheKey">The cache key.</param>
  66. /// <param name="lastDateModified">The last date modified.</param>
  67. /// <param name="cacheDuration">Duration of the cache.</param>
  68. /// <param name="factoryFn">The factory fn.</param>
  69. /// <param name="contentType">Type of the content.</param>
  70. /// <returns>System.Object.</returns>
  71. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  72. protected object ToCachedResult<T>(Guid cacheKey, DateTime lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, string contentType)
  73. where T : class
  74. {
  75. return ResultFactory.GetCachedResult(RequestContext, cacheKey, lastDateModified, cacheDuration, factoryFn, contentType);
  76. }
  77. /// <summary>
  78. /// To the static file result.
  79. /// </summary>
  80. /// <param name="path">The path.</param>
  81. /// <returns>System.Object.</returns>
  82. protected object ToStaticFileResult(string path)
  83. {
  84. return ResultFactory.GetStaticFileResult(RequestContext, path);
  85. }
  86. private readonly char[] _dashReplaceChars = new[] { '?', '/' };
  87. private const char SlugChar = '-';
  88. protected Artist GetArtist(string name, ILibraryManager libraryManager)
  89. {
  90. return libraryManager.GetArtist(DeSlugArtistName(name, libraryManager));
  91. }
  92. protected Studio GetStudio(string name, ILibraryManager libraryManager)
  93. {
  94. return libraryManager.GetStudio(DeSlugStudioName(name, libraryManager));
  95. }
  96. protected Genre GetGenre(string name, ILibraryManager libraryManager)
  97. {
  98. return libraryManager.GetGenre(DeSlugGenreName(name, libraryManager));
  99. }
  100. protected MusicGenre GetMusicGenre(string name, ILibraryManager libraryManager)
  101. {
  102. return libraryManager.GetMusicGenre(DeSlugGenreName(name, libraryManager));
  103. }
  104. protected GameGenre GetGameGenre(string name, ILibraryManager libraryManager)
  105. {
  106. return libraryManager.GetGameGenre(DeSlugGameGenreName(name, libraryManager));
  107. }
  108. protected Person GetPerson(string name, ILibraryManager libraryManager)
  109. {
  110. return libraryManager.GetPerson(DeSlugPersonName(name, libraryManager));
  111. }
  112. protected IEnumerable<BaseItem> GetAllLibraryItems(Guid? userId, IUserManager userManager, ILibraryManager libraryManager)
  113. {
  114. if (userId.HasValue)
  115. {
  116. var user = userManager.GetUserById(userId.Value);
  117. return userManager.GetUserById(userId.Value).RootFolder.GetRecursiveChildren(user);
  118. }
  119. return libraryManager.RootFolder.RecursiveChildren;
  120. }
  121. /// <summary>
  122. /// Deslugs an artist name by finding the correct entry in the library
  123. /// </summary>
  124. /// <param name="name"></param>
  125. /// <param name="libraryManager"></param>
  126. /// <returns></returns>
  127. protected string DeSlugArtistName(string name, ILibraryManager libraryManager)
  128. {
  129. if (name.IndexOf(SlugChar) == -1)
  130. {
  131. return name;
  132. }
  133. return libraryManager.RootFolder.RecursiveChildren
  134. .OfType<Audio>()
  135. .SelectMany(i =>
  136. {
  137. var list = new List<string>();
  138. if (!string.IsNullOrEmpty(i.AlbumArtist))
  139. {
  140. list.Add(i.AlbumArtist);
  141. }
  142. list.AddRange(i.Artists);
  143. return list;
  144. })
  145. .Distinct(StringComparer.OrdinalIgnoreCase)
  146. .FirstOrDefault(i =>
  147. {
  148. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  149. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  150. }) ?? name;
  151. }
  152. /// <summary>
  153. /// Deslugs a genre name by finding the correct entry in the library
  154. /// </summary>
  155. protected string DeSlugGenreName(string name, ILibraryManager libraryManager)
  156. {
  157. if (name.IndexOf(SlugChar) == -1)
  158. {
  159. return name;
  160. }
  161. return libraryManager.RootFolder.RecursiveChildren
  162. .SelectMany(i => i.Genres)
  163. .Distinct(StringComparer.OrdinalIgnoreCase)
  164. .FirstOrDefault(i =>
  165. {
  166. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  167. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  168. }) ?? name;
  169. }
  170. protected string DeSlugGameGenreName(string name, ILibraryManager libraryManager)
  171. {
  172. if (name.IndexOf(SlugChar) == -1)
  173. {
  174. return name;
  175. }
  176. return libraryManager.RootFolder.RecursiveChildren
  177. .OfType<Game>()
  178. .SelectMany(i => i.Genres)
  179. .Distinct(StringComparer.OrdinalIgnoreCase)
  180. .FirstOrDefault(i =>
  181. {
  182. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  183. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  184. }) ?? name;
  185. }
  186. /// <summary>
  187. /// Deslugs a studio name by finding the correct entry in the library
  188. /// </summary>
  189. protected string DeSlugStudioName(string name, ILibraryManager libraryManager)
  190. {
  191. if (name.IndexOf(SlugChar) == -1)
  192. {
  193. return name;
  194. }
  195. return libraryManager.RootFolder.RecursiveChildren
  196. .SelectMany(i => i.Studios)
  197. .Distinct(StringComparer.OrdinalIgnoreCase)
  198. .FirstOrDefault(i =>
  199. {
  200. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  201. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  202. }) ?? name;
  203. }
  204. /// <summary>
  205. /// Deslugs a person name by finding the correct entry in the library
  206. /// </summary>
  207. protected string DeSlugPersonName(string name, ILibraryManager libraryManager)
  208. {
  209. if (name.IndexOf(SlugChar) == -1)
  210. {
  211. return name;
  212. }
  213. return libraryManager.RootFolder.RecursiveChildren
  214. .SelectMany(i => i.People)
  215. .Select(i => i.Name)
  216. .Distinct(StringComparer.OrdinalIgnoreCase)
  217. .FirstOrDefault(i =>
  218. {
  219. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  220. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  221. }) ?? name;
  222. }
  223. /// <summary>
  224. /// Gets the name of the item by.
  225. /// </summary>
  226. /// <param name="name">The name.</param>
  227. /// <param name="type">The type.</param>
  228. /// <param name="libraryManager">The library manager.</param>
  229. /// <returns>Task{BaseItem}.</returns>
  230. /// <exception cref="System.ArgumentException"></exception>
  231. protected BaseItem GetItemByName(string name, string type, ILibraryManager libraryManager)
  232. {
  233. BaseItem item;
  234. if (type.IndexOf("Person", StringComparison.OrdinalIgnoreCase) == 0)
  235. {
  236. item = GetPerson(name, libraryManager);
  237. }
  238. else if (type.IndexOf("Artist", StringComparison.OrdinalIgnoreCase) == 0)
  239. {
  240. item = GetArtist(name, libraryManager);
  241. }
  242. else if (type.IndexOf("Genre", StringComparison.OrdinalIgnoreCase) == 0)
  243. {
  244. item = GetGenre(name, libraryManager);
  245. }
  246. else if (type.IndexOf("MusicGenre", StringComparison.OrdinalIgnoreCase) == 0)
  247. {
  248. item = GetMusicGenre(name, libraryManager);
  249. }
  250. else if (type.IndexOf("GameGenre", StringComparison.OrdinalIgnoreCase) == 0)
  251. {
  252. item = GetGameGenre(name, libraryManager);
  253. }
  254. else if (type.IndexOf("Studio", StringComparison.OrdinalIgnoreCase) == 0)
  255. {
  256. item = GetStudio(name, libraryManager);
  257. }
  258. else if (type.IndexOf("Year", StringComparison.OrdinalIgnoreCase) == 0)
  259. {
  260. item = libraryManager.GetYear(int.Parse(name));
  261. }
  262. else
  263. {
  264. throw new ArgumentException();
  265. }
  266. return item;
  267. }
  268. }
  269. /// <summary>
  270. /// Class RequestFilterAttribute
  271. /// </summary>
  272. public class RequestFilterAttribute : Attribute, IHasRequestFilter
  273. {
  274. //This property will be resolved by the IoC container
  275. /// <summary>
  276. /// Gets or sets the user manager.
  277. /// </summary>
  278. /// <value>The user manager.</value>
  279. public IUserManager UserManager { get; set; }
  280. public ISessionManager SessionManager { get; set; }
  281. /// <summary>
  282. /// Gets or sets the logger.
  283. /// </summary>
  284. /// <value>The logger.</value>
  285. public ILogger Logger { get; set; }
  286. /// <summary>
  287. /// The request filter is executed before the service.
  288. /// </summary>
  289. /// <param name="request">The http request wrapper</param>
  290. /// <param name="response">The http response wrapper</param>
  291. /// <param name="requestDto">The request DTO</param>
  292. public void RequestFilter(IHttpRequest request, IHttpResponse response, object requestDto)
  293. {
  294. //This code is executed before the service
  295. var auth = GetAuthorization(request);
  296. if (auth != null)
  297. {
  298. User user = null;
  299. if (auth.ContainsKey("UserId"))
  300. {
  301. var userId = auth["UserId"];
  302. if (!string.IsNullOrEmpty(userId))
  303. {
  304. user = UserManager.GetUserById(new Guid(userId));
  305. }
  306. }
  307. string deviceId;
  308. string device;
  309. string client;
  310. string version;
  311. auth.TryGetValue("DeviceId", out deviceId);
  312. auth.TryGetValue("Device", out device);
  313. auth.TryGetValue("Client", out client);
  314. auth.TryGetValue("Version", out version);
  315. if (!string.IsNullOrEmpty(client) && !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(device) && !string.IsNullOrEmpty(version))
  316. {
  317. SessionManager.LogConnectionActivity(client, version, deviceId, device, user);
  318. }
  319. }
  320. }
  321. /// <summary>
  322. /// Gets the auth.
  323. /// </summary>
  324. /// <param name="httpReq">The HTTP req.</param>
  325. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  326. public static Dictionary<string, string> GetAuthorization(IHttpRequest httpReq)
  327. {
  328. var auth = httpReq.Headers[HttpHeaders.Authorization];
  329. return GetAuthorization(auth);
  330. }
  331. /// <summary>
  332. /// Gets the authorization.
  333. /// </summary>
  334. /// <param name="httpReq">The HTTP req.</param>
  335. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  336. public static Dictionary<string, string> GetAuthorization(IRequestContext httpReq)
  337. {
  338. var auth = httpReq.GetHeader("Authorization");
  339. return GetAuthorization(auth);
  340. }
  341. /// <summary>
  342. /// Gets the authorization.
  343. /// </summary>
  344. /// <param name="authorizationHeader">The authorization header.</param>
  345. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  346. private static Dictionary<string, string> GetAuthorization(string authorizationHeader)
  347. {
  348. if (authorizationHeader == null) return null;
  349. var parts = authorizationHeader.Split(' ');
  350. // There should be at least to parts
  351. if (parts.Length < 2) return null;
  352. // It has to be a digest request
  353. if (!string.Equals(parts[0], "MediaBrowser", StringComparison.OrdinalIgnoreCase))
  354. {
  355. return null;
  356. }
  357. // Remove uptil the first space
  358. authorizationHeader = authorizationHeader.Substring(authorizationHeader.IndexOf(' '));
  359. parts = authorizationHeader.Split(',');
  360. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  361. foreach (var item in parts)
  362. {
  363. var param = item.Trim().Split(new[] { '=' }, 2);
  364. result.Add(param[0], param[1].Trim(new[] { '"' }));
  365. }
  366. return result;
  367. }
  368. /// <summary>
  369. /// A new shallow copy of this filter is used on every request.
  370. /// </summary>
  371. /// <returns>IHasRequestFilter.</returns>
  372. public IHasRequestFilter Copy()
  373. {
  374. return this;
  375. }
  376. /// <summary>
  377. /// Order in which Request Filters are executed.
  378. /// &lt;0 Executed before global request filters
  379. /// &gt;0 Executed after global request filters
  380. /// </summary>
  381. /// <value>The priority.</value>
  382. public int Priority
  383. {
  384. get { return 0; }
  385. }
  386. }
  387. }