BaseApiService.cs 8.0 KB

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