BaseApiService.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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)
  113. {
  114. User user = null;
  115. if (auth.ContainsKey("UserId"))
  116. {
  117. user = UserManager.GetUserById(new Guid(auth["UserId"]));
  118. }
  119. var deviceId = auth["DeviceId"];
  120. var device = auth["Device"];
  121. var client = auth["Client"];
  122. if (!string.IsNullOrEmpty(client) && !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(device))
  123. {
  124. SessionManager.LogConnectionActivity(client, deviceId, device, user);
  125. }
  126. }
  127. }
  128. /// <summary>
  129. /// Gets the auth.
  130. /// </summary>
  131. /// <param name="httpReq">The HTTP req.</param>
  132. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  133. public static Dictionary<string, string> GetAuthorization(IHttpRequest httpReq)
  134. {
  135. var auth = httpReq.Headers[HttpHeaders.Authorization];
  136. return GetAuthorization(auth);
  137. }
  138. /// <summary>
  139. /// Gets the authorization.
  140. /// </summary>
  141. /// <param name="httpReq">The HTTP req.</param>
  142. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  143. public static Dictionary<string, string> GetAuthorization(IRequestContext httpReq)
  144. {
  145. var auth = httpReq.GetHeader("Authorization");
  146. return GetAuthorization(auth);
  147. }
  148. /// <summary>
  149. /// Gets the authorization.
  150. /// </summary>
  151. /// <param name="authorizationHeader">The authorization header.</param>
  152. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  153. private static Dictionary<string, string> GetAuthorization(string authorizationHeader)
  154. {
  155. if (authorizationHeader == null) return null;
  156. var parts = authorizationHeader.Split(' ');
  157. // There should be at least to parts
  158. if (parts.Length < 2) return null;
  159. // It has to be a digest request
  160. if (!string.Equals(parts[0], "MediaBrowser", StringComparison.OrdinalIgnoreCase))
  161. {
  162. return null;
  163. }
  164. // Remove uptil the first space
  165. authorizationHeader = authorizationHeader.Substring(authorizationHeader.IndexOf(' '));
  166. parts = authorizationHeader.Split(',');
  167. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  168. foreach (var item in parts)
  169. {
  170. var param = item.Trim().Split(new[] { '=' }, 2);
  171. result.Add(param[0], param[1].Trim(new[] { '"' }));
  172. }
  173. return result;
  174. }
  175. /// <summary>
  176. /// A new shallow copy of this filter is used on every request.
  177. /// </summary>
  178. /// <returns>IHasRequestFilter.</returns>
  179. public IHasRequestFilter Copy()
  180. {
  181. return this;
  182. }
  183. /// <summary>
  184. /// Order in which Request Filters are executed.
  185. /// &lt;0 Executed before global request filters
  186. /// &gt;0 Executed after global request filters
  187. /// </summary>
  188. /// <value>The priority.</value>
  189. public int Priority
  190. {
  191. get { return 0; }
  192. }
  193. }
  194. }