BaseApiService.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Library;
  3. using MediaBrowser.Model.Logging;
  4. using ServiceStack.Common.Web;
  5. using ServiceStack.ServiceHost;
  6. using System;
  7. using System.Collections.Generic;
  8. namespace MediaBrowser.Api
  9. {
  10. /// <summary>
  11. /// Class BaseApiService
  12. /// </summary>
  13. [RequestFilter]
  14. public class BaseApiService : IHasResultFactory, IRestfulService
  15. {
  16. /// <summary>
  17. /// Gets or sets the logger.
  18. /// </summary>
  19. /// <value>The logger.</value>
  20. public ILogger Logger { get; set; }
  21. /// <summary>
  22. /// Gets or sets the HTTP result factory.
  23. /// </summary>
  24. /// <value>The HTTP result factory.</value>
  25. public IHttpResultFactory ResultFactory { get; set; }
  26. /// <summary>
  27. /// Gets or sets the request context.
  28. /// </summary>
  29. /// <value>The request context.</value>
  30. public IRequestContext RequestContext { get; set; }
  31. /// <summary>
  32. /// To the optimized result.
  33. /// </summary>
  34. /// <typeparam name="T"></typeparam>
  35. /// <param name="result">The result.</param>
  36. /// <returns>System.Object.</returns>
  37. protected object ToOptimizedResult<T>(T result)
  38. where T : class
  39. {
  40. return ResultFactory.GetOptimizedResult(RequestContext, result);
  41. }
  42. /// <summary>
  43. /// To the optimized result using cache.
  44. /// </summary>
  45. /// <typeparam name="T"></typeparam>
  46. /// <param name="cacheKey">The cache key.</param>
  47. /// <param name="lastDateModified">The last date modified.</param>
  48. /// <param name="cacheDuration">Duration of the cache.</param>
  49. /// <param name="factoryFn">The factory fn.</param>
  50. /// <returns>System.Object.</returns>
  51. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  52. protected object ToOptimizedResultUsingCache<T>(Guid cacheKey, DateTime lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn)
  53. where T : class
  54. {
  55. return ResultFactory.GetOptimizedResultUsingCache(RequestContext, cacheKey, lastDateModified, cacheDuration, factoryFn);
  56. }
  57. /// <summary>
  58. /// To the cached result.
  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. /// <param name="contentType">Type of the content.</param>
  66. /// <returns>System.Object.</returns>
  67. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  68. protected object ToCachedResult<T>(Guid cacheKey, DateTime lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, string contentType)
  69. where T : class
  70. {
  71. return ResultFactory.GetCachedResult(RequestContext, cacheKey, lastDateModified, cacheDuration, factoryFn, contentType);
  72. }
  73. }
  74. /// <summary>
  75. /// Class RequestFilterAttribute
  76. /// </summary>
  77. public class RequestFilterAttribute : Attribute, IHasRequestFilter
  78. {
  79. //This property will be resolved by the IoC container
  80. /// <summary>
  81. /// Gets or sets the user manager.
  82. /// </summary>
  83. /// <value>The user manager.</value>
  84. public IUserManager UserManager { get; set; }
  85. /// <summary>
  86. /// Gets or sets the logger.
  87. /// </summary>
  88. /// <value>The logger.</value>
  89. public ILogger Logger { get; set; }
  90. /// <summary>
  91. /// The request filter is executed before the service.
  92. /// </summary>
  93. /// <param name="request">The http request wrapper</param>
  94. /// <param name="response">The http response wrapper</param>
  95. /// <param name="requestDto">The request DTO</param>
  96. public void RequestFilter(IHttpRequest request, IHttpResponse response, object requestDto)
  97. {
  98. //This code is executed before the service
  99. var auth = GetAuthorization(request);
  100. if (auth != null && auth.ContainsKey("UserId"))
  101. {
  102. var userId = auth["UserId"];
  103. if (!string.IsNullOrEmpty(userId))
  104. {
  105. var user = UserManager.GetUserById(new Guid(userId));
  106. UserManager.LogUserActivity(user, auth["Client"], auth["DeviceId"], auth["Device"] ?? string.Empty);
  107. }
  108. }
  109. }
  110. /// <summary>
  111. /// Gets the auth.
  112. /// </summary>
  113. /// <param name="httpReq">The HTTP req.</param>
  114. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  115. public static Dictionary<string, string> GetAuthorization(IHttpRequest httpReq)
  116. {
  117. var auth = httpReq.Headers[HttpHeaders.Authorization];
  118. return GetAuthorization(auth);
  119. }
  120. /// <summary>
  121. /// Gets the authorization.
  122. /// </summary>
  123. /// <param name="httpReq">The HTTP req.</param>
  124. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  125. public static Dictionary<string, string> GetAuthorization(IRequestContext httpReq)
  126. {
  127. var auth = httpReq.GetHeader("Authorization");
  128. return GetAuthorization(auth);
  129. }
  130. /// <summary>
  131. /// Gets the authorization.
  132. /// </summary>
  133. /// <param name="authorizationHeader">The authorization header.</param>
  134. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  135. private static Dictionary<string, string> GetAuthorization(string authorizationHeader)
  136. {
  137. if (authorizationHeader == null) return null;
  138. var parts = authorizationHeader.Split(' ');
  139. // There should be at least to parts
  140. if (parts.Length < 2) return null;
  141. // It has to be a digest request
  142. if (!string.Equals(parts[0], "MediaBrowser", StringComparison.OrdinalIgnoreCase))
  143. {
  144. return null;
  145. }
  146. // Remove uptil the first space
  147. authorizationHeader = authorizationHeader.Substring(authorizationHeader.IndexOf(' '));
  148. parts = authorizationHeader.Split(',');
  149. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  150. foreach (var item in parts)
  151. {
  152. var param = item.Trim().Split(new[] { '=' }, 2);
  153. result.Add(param[0], param[1].Trim(new[] { '"' }));
  154. }
  155. return result;
  156. }
  157. /// <summary>
  158. /// A new shallow copy of this filter is used on every request.
  159. /// </summary>
  160. /// <returns>IHasRequestFilter.</returns>
  161. public IHasRequestFilter Copy()
  162. {
  163. return this;
  164. }
  165. /// <summary>
  166. /// Order in which Request Filters are executed.
  167. /// &lt;0 Executed before global request filters
  168. /// &gt;0 Executed after global request filters
  169. /// </summary>
  170. /// <value>The priority.</value>
  171. public int Priority
  172. {
  173. get { return 0; }
  174. }
  175. }
  176. }