BaseApiService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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 Artist GetArtist(string name, ILibraryManager libraryManager)
  90. {
  91. return libraryManager.GetArtist(DeSlugArtistName(name, libraryManager));
  92. }
  93. protected Studio GetStudio(string name, ILibraryManager libraryManager)
  94. {
  95. return libraryManager.GetStudio(DeSlugStudioName(name, libraryManager));
  96. }
  97. protected Genre GetGenre(string name, ILibraryManager libraryManager)
  98. {
  99. return libraryManager.GetGenre(DeSlugGenreName(name, libraryManager));
  100. }
  101. protected MusicGenre GetMusicGenre(string name, ILibraryManager libraryManager)
  102. {
  103. return libraryManager.GetMusicGenre(DeSlugGenreName(name, libraryManager));
  104. }
  105. protected GameGenre GetGameGenre(string name, ILibraryManager libraryManager)
  106. {
  107. return libraryManager.GetGameGenre(DeSlugGameGenreName(name, libraryManager));
  108. }
  109. protected Person GetPerson(string name, ILibraryManager libraryManager)
  110. {
  111. return libraryManager.GetPerson(DeSlugPersonName(name, libraryManager));
  112. }
  113. /// <summary>
  114. /// Deslugs an artist name by finding the correct entry in the library
  115. /// </summary>
  116. /// <param name="name"></param>
  117. /// <param name="libraryManager"></param>
  118. /// <returns></returns>
  119. protected string DeSlugArtistName(string name, ILibraryManager libraryManager)
  120. {
  121. if (name.IndexOf(SlugChar) == -1)
  122. {
  123. return name;
  124. }
  125. return libraryManager.RootFolder.RecursiveChildren
  126. .OfType<Audio>()
  127. .SelectMany(i =>
  128. {
  129. var list = new List<string>();
  130. if (!string.IsNullOrEmpty(i.AlbumArtist))
  131. {
  132. list.Add(i.AlbumArtist);
  133. }
  134. list.AddRange(i.Artists);
  135. return list;
  136. })
  137. .Distinct(StringComparer.OrdinalIgnoreCase)
  138. .FirstOrDefault(i =>
  139. {
  140. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  141. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  142. }) ?? name;
  143. }
  144. /// <summary>
  145. /// Deslugs a genre name by finding the correct entry in the library
  146. /// </summary>
  147. protected string DeSlugGenreName(string name, ILibraryManager libraryManager)
  148. {
  149. if (name.IndexOf(SlugChar) == -1)
  150. {
  151. return name;
  152. }
  153. return libraryManager.RootFolder.RecursiveChildren
  154. .SelectMany(i => i.Genres)
  155. .Distinct(StringComparer.OrdinalIgnoreCase)
  156. .FirstOrDefault(i =>
  157. {
  158. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  159. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  160. }) ?? name;
  161. }
  162. protected string DeSlugGameGenreName(string name, ILibraryManager libraryManager)
  163. {
  164. if (name.IndexOf(SlugChar) == -1)
  165. {
  166. return name;
  167. }
  168. return libraryManager.RootFolder.RecursiveChildren
  169. .OfType<Game>()
  170. .SelectMany(i => i.Genres)
  171. .Distinct(StringComparer.OrdinalIgnoreCase)
  172. .FirstOrDefault(i =>
  173. {
  174. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  175. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  176. }) ?? name;
  177. }
  178. /// <summary>
  179. /// Deslugs a studio name by finding the correct entry in the library
  180. /// </summary>
  181. protected string DeSlugStudioName(string name, ILibraryManager libraryManager)
  182. {
  183. if (name.IndexOf(SlugChar) == -1)
  184. {
  185. return name;
  186. }
  187. return libraryManager.RootFolder.RecursiveChildren
  188. .SelectMany(i => i.Studios)
  189. .Distinct(StringComparer.OrdinalIgnoreCase)
  190. .FirstOrDefault(i =>
  191. {
  192. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  193. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  194. }) ?? name;
  195. }
  196. /// <summary>
  197. /// Deslugs a person name by finding the correct entry in the library
  198. /// </summary>
  199. protected string DeSlugPersonName(string name, ILibraryManager libraryManager)
  200. {
  201. if (name.IndexOf(SlugChar) == -1)
  202. {
  203. return name;
  204. }
  205. return libraryManager.RootFolder.RecursiveChildren
  206. .SelectMany(i => i.People)
  207. .Select(i => i.Name)
  208. .Distinct(StringComparer.OrdinalIgnoreCase)
  209. .FirstOrDefault(i =>
  210. {
  211. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  212. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  213. }) ?? name;
  214. }
  215. /// <summary>
  216. /// Gets the name of the item by.
  217. /// </summary>
  218. /// <param name="name">The name.</param>
  219. /// <param name="type">The type.</param>
  220. /// <param name="libraryManager">The library manager.</param>
  221. /// <returns>Task{BaseItem}.</returns>
  222. /// <exception cref="System.ArgumentException"></exception>
  223. protected BaseItem GetItemByName(string name, string type, ILibraryManager libraryManager)
  224. {
  225. BaseItem item;
  226. if (type.IndexOf("Person", StringComparison.OrdinalIgnoreCase) == 0)
  227. {
  228. item = GetPerson(name, libraryManager);
  229. }
  230. else if (type.IndexOf("Artist", StringComparison.OrdinalIgnoreCase) == 0)
  231. {
  232. item = GetArtist(name, libraryManager);
  233. }
  234. else if (type.IndexOf("Genre", StringComparison.OrdinalIgnoreCase) == 0)
  235. {
  236. item = GetGenre(name, libraryManager);
  237. }
  238. else if (type.IndexOf("MusicGenre", StringComparison.OrdinalIgnoreCase) == 0)
  239. {
  240. item = GetMusicGenre(name, libraryManager);
  241. }
  242. else if (type.IndexOf("GameGenre", StringComparison.OrdinalIgnoreCase) == 0)
  243. {
  244. item = GetGameGenre(name, libraryManager);
  245. }
  246. else if (type.IndexOf("Studio", StringComparison.OrdinalIgnoreCase) == 0)
  247. {
  248. item = GetStudio(name, libraryManager);
  249. }
  250. else if (type.IndexOf("Year", StringComparison.OrdinalIgnoreCase) == 0)
  251. {
  252. item = libraryManager.GetYear(int.Parse(name));
  253. }
  254. else
  255. {
  256. throw new ArgumentException();
  257. }
  258. return item;
  259. }
  260. }
  261. /// <summary>
  262. /// Class RequestFilterAttribute
  263. /// </summary>
  264. public class RequestFilterAttribute : Attribute, IHasRequestFilter
  265. {
  266. //This property will be resolved by the IoC container
  267. /// <summary>
  268. /// Gets or sets the user manager.
  269. /// </summary>
  270. /// <value>The user manager.</value>
  271. public IUserManager UserManager { get; set; }
  272. public ISessionManager SessionManager { get; set; }
  273. /// <summary>
  274. /// Gets or sets the logger.
  275. /// </summary>
  276. /// <value>The logger.</value>
  277. public ILogger Logger { get; set; }
  278. /// <summary>
  279. /// The request filter is executed before the service.
  280. /// </summary>
  281. /// <param name="request">The http request wrapper</param>
  282. /// <param name="response">The http response wrapper</param>
  283. /// <param name="requestDto">The request DTO</param>
  284. public void RequestFilter(IHttpRequest request, IHttpResponse response, object requestDto)
  285. {
  286. //This code is executed before the service
  287. var auth = GetAuthorization(request);
  288. if (auth != null)
  289. {
  290. User user = null;
  291. if (auth.ContainsKey("UserId"))
  292. {
  293. var userId = auth["UserId"];
  294. if (!string.IsNullOrEmpty(userId))
  295. {
  296. user = UserManager.GetUserById(new Guid(userId));
  297. }
  298. }
  299. string deviceId;
  300. string device;
  301. string client;
  302. string version;
  303. auth.TryGetValue("DeviceId", out deviceId);
  304. auth.TryGetValue("Device", out device);
  305. auth.TryGetValue("Client", out client);
  306. auth.TryGetValue("Version", out version);
  307. if (!string.IsNullOrEmpty(client) && !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(device) && !string.IsNullOrEmpty(version))
  308. {
  309. SessionManager.LogConnectionActivity(client, version, deviceId, device, user);
  310. }
  311. }
  312. }
  313. /// <summary>
  314. /// Gets the auth.
  315. /// </summary>
  316. /// <param name="httpReq">The HTTP req.</param>
  317. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  318. public static Dictionary<string, string> GetAuthorization(IHttpRequest httpReq)
  319. {
  320. var auth = httpReq.Headers[HttpHeaders.Authorization];
  321. return GetAuthorization(auth);
  322. }
  323. /// <summary>
  324. /// Gets the authorization.
  325. /// </summary>
  326. /// <param name="httpReq">The HTTP req.</param>
  327. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  328. public static Dictionary<string, string> GetAuthorization(IRequestContext httpReq)
  329. {
  330. var auth = httpReq.GetHeader("Authorization");
  331. return GetAuthorization(auth);
  332. }
  333. /// <summary>
  334. /// Gets the authorization.
  335. /// </summary>
  336. /// <param name="authorizationHeader">The authorization header.</param>
  337. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  338. private static Dictionary<string, string> GetAuthorization(string authorizationHeader)
  339. {
  340. if (authorizationHeader == null) return null;
  341. var parts = authorizationHeader.Split(' ');
  342. // There should be at least to parts
  343. if (parts.Length < 2) return null;
  344. // It has to be a digest request
  345. if (!string.Equals(parts[0], "MediaBrowser", StringComparison.OrdinalIgnoreCase))
  346. {
  347. return null;
  348. }
  349. // Remove uptil the first space
  350. authorizationHeader = authorizationHeader.Substring(authorizationHeader.IndexOf(' '));
  351. parts = authorizationHeader.Split(',');
  352. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  353. foreach (var item in parts)
  354. {
  355. var param = item.Trim().Split(new[] { '=' }, 2);
  356. result.Add(param[0], param[1].Trim(new[] { '"' }));
  357. }
  358. return result;
  359. }
  360. /// <summary>
  361. /// A new shallow copy of this filter is used on every request.
  362. /// </summary>
  363. /// <returns>IHasRequestFilter.</returns>
  364. public IHasRequestFilter Copy()
  365. {
  366. return this;
  367. }
  368. /// <summary>
  369. /// Order in which Request Filters are executed.
  370. /// &lt;0 Executed before global request filters
  371. /// &gt;0 Executed after global request filters
  372. /// </summary>
  373. /// <value>The priority.</value>
  374. public int Priority
  375. {
  376. get { return 0; }
  377. }
  378. }
  379. }