2
0

BaseApiService.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. /// <summary>
  74. /// To the static file result.
  75. /// </summary>
  76. /// <param name="path">The path.</param>
  77. /// <returns>System.Object.</returns>
  78. protected object ToStaticFileResult(string path)
  79. {
  80. return ResultFactory.GetStaticFileResult(RequestContext, path);
  81. }
  82. }
  83. /// <summary>
  84. /// Class RequestFilterAttribute
  85. /// </summary>
  86. public class RequestFilterAttribute : Attribute, IHasRequestFilter
  87. {
  88. //This property will be resolved by the IoC container
  89. /// <summary>
  90. /// Gets or sets the user manager.
  91. /// </summary>
  92. /// <value>The user manager.</value>
  93. public IUserManager UserManager { get; set; }
  94. /// <summary>
  95. /// Gets or sets the logger.
  96. /// </summary>
  97. /// <value>The logger.</value>
  98. public ILogger Logger { get; set; }
  99. /// <summary>
  100. /// The request filter is executed before the service.
  101. /// </summary>
  102. /// <param name="request">The http request wrapper</param>
  103. /// <param name="response">The http response wrapper</param>
  104. /// <param name="requestDto">The request DTO</param>
  105. public void RequestFilter(IHttpRequest request, IHttpResponse response, object requestDto)
  106. {
  107. //This code is executed before the service
  108. var auth = GetAuthorization(request);
  109. if (auth != null && auth.ContainsKey("UserId"))
  110. {
  111. var userId = auth["UserId"];
  112. if (!string.IsNullOrEmpty(userId))
  113. {
  114. var user = UserManager.GetUserById(new Guid(userId));
  115. UserManager.LogUserActivity(user, auth["Client"], auth["DeviceId"], auth["Device"] ?? string.Empty);
  116. }
  117. }
  118. }
  119. /// <summary>
  120. /// Gets the auth.
  121. /// </summary>
  122. /// <param name="httpReq">The HTTP req.</param>
  123. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  124. public static Dictionary<string, string> GetAuthorization(IHttpRequest httpReq)
  125. {
  126. var auth = httpReq.Headers[HttpHeaders.Authorization];
  127. return GetAuthorization(auth);
  128. }
  129. /// <summary>
  130. /// Gets the authorization.
  131. /// </summary>
  132. /// <param name="httpReq">The HTTP req.</param>
  133. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  134. public static Dictionary<string, string> GetAuthorization(IRequestContext httpReq)
  135. {
  136. var auth = httpReq.GetHeader("Authorization");
  137. return GetAuthorization(auth);
  138. }
  139. /// <summary>
  140. /// Gets the authorization.
  141. /// </summary>
  142. /// <param name="authorizationHeader">The authorization header.</param>
  143. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  144. private static Dictionary<string, string> GetAuthorization(string authorizationHeader)
  145. {
  146. if (authorizationHeader == null) return null;
  147. var parts = authorizationHeader.Split(' ');
  148. // There should be at least to parts
  149. if (parts.Length < 2) return null;
  150. // It has to be a digest request
  151. if (!string.Equals(parts[0], "MediaBrowser", StringComparison.OrdinalIgnoreCase))
  152. {
  153. return null;
  154. }
  155. // Remove uptil the first space
  156. authorizationHeader = authorizationHeader.Substring(authorizationHeader.IndexOf(' '));
  157. parts = authorizationHeader.Split(',');
  158. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  159. foreach (var item in parts)
  160. {
  161. var param = item.Trim().Split(new[] { '=' }, 2);
  162. result.Add(param[0], param[1].Trim(new[] { '"' }));
  163. }
  164. return result;
  165. }
  166. /// <summary>
  167. /// A new shallow copy of this filter is used on every request.
  168. /// </summary>
  169. /// <returns>IHasRequestFilter.</returns>
  170. public IHasRequestFilter Copy()
  171. {
  172. return this;
  173. }
  174. /// <summary>
  175. /// Order in which Request Filters are executed.
  176. /// &lt;0 Executed before global request filters
  177. /// &gt;0 Executed after global request filters
  178. /// </summary>
  179. /// <value>The priority.</value>
  180. public int Priority
  181. {
  182. get { return 0; }
  183. }
  184. }
  185. }