2
0

BaseApiService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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<MusicGenre> GetMusicGenre(string name, ILibraryManager libraryManager)
  102. {
  103. return libraryManager.GetMusicGenre(DeSlugGenreName(name, libraryManager));
  104. }
  105. protected Task<Person> GetPerson(string name, ILibraryManager libraryManager)
  106. {
  107. return libraryManager.GetPerson(DeSlugPersonName(name, libraryManager));
  108. }
  109. /// <summary>
  110. /// Deslugs an artist name by finding the correct entry in the library
  111. /// </summary>
  112. /// <param name="name"></param>
  113. /// <param name="libraryManager"></param>
  114. /// <returns></returns>
  115. protected string DeSlugArtistName(string name, ILibraryManager libraryManager)
  116. {
  117. if (name.IndexOf(SlugChar) == -1)
  118. {
  119. return name;
  120. }
  121. return libraryManager.RootFolder.RecursiveChildren
  122. .OfType<Audio>()
  123. .SelectMany(i => new[] { i.Artist, i.AlbumArtist })
  124. .Where(i => !string.IsNullOrEmpty(i))
  125. .Distinct(StringComparer.OrdinalIgnoreCase)
  126. .FirstOrDefault(i =>
  127. {
  128. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  129. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  130. }) ?? name;
  131. }
  132. /// <summary>
  133. /// Deslugs a genre name by finding the correct entry in the library
  134. /// </summary>
  135. protected string DeSlugGenreName(string name, ILibraryManager libraryManager)
  136. {
  137. if (name.IndexOf(SlugChar) == -1)
  138. {
  139. return name;
  140. }
  141. return libraryManager.RootFolder.RecursiveChildren
  142. .SelectMany(i => i.Genres)
  143. .Distinct(StringComparer.OrdinalIgnoreCase)
  144. .FirstOrDefault(i =>
  145. {
  146. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  147. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  148. }) ?? name;
  149. }
  150. /// <summary>
  151. /// Deslugs a studio name by finding the correct entry in the library
  152. /// </summary>
  153. protected string DeSlugStudioName(string name, ILibraryManager libraryManager)
  154. {
  155. if (name.IndexOf(SlugChar) == -1)
  156. {
  157. return name;
  158. }
  159. return libraryManager.RootFolder.RecursiveChildren
  160. .SelectMany(i => i.Studios)
  161. .Distinct(StringComparer.OrdinalIgnoreCase)
  162. .FirstOrDefault(i =>
  163. {
  164. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  165. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  166. }) ?? name;
  167. }
  168. /// <summary>
  169. /// Deslugs a person name by finding the correct entry in the library
  170. /// </summary>
  171. protected string DeSlugPersonName(string name, ILibraryManager libraryManager)
  172. {
  173. if (name.IndexOf(SlugChar) == -1)
  174. {
  175. return name;
  176. }
  177. return libraryManager.RootFolder.RecursiveChildren
  178. .SelectMany(i => i.People)
  179. .Select(i => i.Name)
  180. .Distinct(StringComparer.OrdinalIgnoreCase)
  181. .FirstOrDefault(i =>
  182. {
  183. i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
  184. return string.Equals(i, name, StringComparison.OrdinalIgnoreCase);
  185. }) ?? name;
  186. }
  187. }
  188. /// <summary>
  189. /// Class RequestFilterAttribute
  190. /// </summary>
  191. public class RequestFilterAttribute : Attribute, IHasRequestFilter
  192. {
  193. //This property will be resolved by the IoC container
  194. /// <summary>
  195. /// Gets or sets the user manager.
  196. /// </summary>
  197. /// <value>The user manager.</value>
  198. public IUserManager UserManager { get; set; }
  199. public ISessionManager SessionManager { get; set; }
  200. /// <summary>
  201. /// Gets or sets the logger.
  202. /// </summary>
  203. /// <value>The logger.</value>
  204. public ILogger Logger { get; set; }
  205. /// <summary>
  206. /// The request filter is executed before the service.
  207. /// </summary>
  208. /// <param name="request">The http request wrapper</param>
  209. /// <param name="response">The http response wrapper</param>
  210. /// <param name="requestDto">The request DTO</param>
  211. public void RequestFilter(IHttpRequest request, IHttpResponse response, object requestDto)
  212. {
  213. //This code is executed before the service
  214. var auth = GetAuthorization(request);
  215. if (auth != null)
  216. {
  217. User user = null;
  218. if (auth.ContainsKey("UserId"))
  219. {
  220. var userId = auth["UserId"];
  221. if (!string.IsNullOrEmpty(userId))
  222. {
  223. user = UserManager.GetUserById(new Guid(userId));
  224. }
  225. }
  226. var deviceId = auth["DeviceId"];
  227. var device = auth["Device"];
  228. var client = auth["Client"];
  229. if (!string.IsNullOrEmpty(client) && !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(device))
  230. {
  231. SessionManager.LogConnectionActivity(client, deviceId, device, user);
  232. }
  233. }
  234. }
  235. /// <summary>
  236. /// Gets the auth.
  237. /// </summary>
  238. /// <param name="httpReq">The HTTP req.</param>
  239. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  240. public static Dictionary<string, string> GetAuthorization(IHttpRequest httpReq)
  241. {
  242. var auth = httpReq.Headers[HttpHeaders.Authorization];
  243. return GetAuthorization(auth);
  244. }
  245. /// <summary>
  246. /// Gets the authorization.
  247. /// </summary>
  248. /// <param name="httpReq">The HTTP req.</param>
  249. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  250. public static Dictionary<string, string> GetAuthorization(IRequestContext httpReq)
  251. {
  252. var auth = httpReq.GetHeader("Authorization");
  253. return GetAuthorization(auth);
  254. }
  255. /// <summary>
  256. /// Gets the authorization.
  257. /// </summary>
  258. /// <param name="authorizationHeader">The authorization header.</param>
  259. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  260. private static Dictionary<string, string> GetAuthorization(string authorizationHeader)
  261. {
  262. if (authorizationHeader == null) return null;
  263. var parts = authorizationHeader.Split(' ');
  264. // There should be at least to parts
  265. if (parts.Length < 2) return null;
  266. // It has to be a digest request
  267. if (!string.Equals(parts[0], "MediaBrowser", StringComparison.OrdinalIgnoreCase))
  268. {
  269. return null;
  270. }
  271. // Remove uptil the first space
  272. authorizationHeader = authorizationHeader.Substring(authorizationHeader.IndexOf(' '));
  273. parts = authorizationHeader.Split(',');
  274. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  275. foreach (var item in parts)
  276. {
  277. var param = item.Trim().Split(new[] { '=' }, 2);
  278. result.Add(param[0], param[1].Trim(new[] { '"' }));
  279. }
  280. return result;
  281. }
  282. /// <summary>
  283. /// A new shallow copy of this filter is used on every request.
  284. /// </summary>
  285. /// <returns>IHasRequestFilter.</returns>
  286. public IHasRequestFilter Copy()
  287. {
  288. return this;
  289. }
  290. /// <summary>
  291. /// Order in which Request Filters are executed.
  292. /// &lt;0 Executed before global request filters
  293. /// &gt;0 Executed after global request filters
  294. /// </summary>
  295. /// <value>The priority.</value>
  296. public int Priority
  297. {
  298. get { return 0; }
  299. }
  300. }
  301. }