ServiceController.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Threading.Tasks;
  5. using Emby.Server.Implementations.HttpServer;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Services;
  8. namespace Emby.Server.Implementations.Services
  9. {
  10. public delegate Task<object> InstanceExecFn(IRequest requestContext, object intance, object request);
  11. public delegate object ActionInvokerFn(object intance, object request);
  12. public delegate void VoidActionInvokerFn(object intance, object request);
  13. public class ServiceController
  14. {
  15. public static ServiceController Instance;
  16. public ServiceController()
  17. {
  18. Instance = this;
  19. }
  20. public void Init(HttpListenerHost appHost, Type[] serviceTypes)
  21. {
  22. foreach (var serviceType in serviceTypes)
  23. {
  24. RegisterService(appHost, serviceType);
  25. }
  26. }
  27. private Type[] GetGenericArguments(Type type)
  28. {
  29. return type.GetTypeInfo().IsGenericTypeDefinition
  30. ? type.GetTypeInfo().GenericTypeParameters
  31. : type.GetTypeInfo().GenericTypeArguments;
  32. }
  33. public void RegisterService(HttpListenerHost appHost, Type serviceType)
  34. {
  35. var processedReqs = new HashSet<Type>();
  36. var actions = ServiceExecGeneral.Reset(serviceType);
  37. foreach (var mi in serviceType.GetActions())
  38. {
  39. var requestType = mi.GetParameters()[0].ParameterType;
  40. if (processedReqs.Contains(requestType)) continue;
  41. processedReqs.Add(requestType);
  42. ServiceExecGeneral.CreateServiceRunnersFor(requestType, actions);
  43. var returnMarker = GetTypeWithGenericTypeDefinitionOf(requestType, typeof(IReturn<>));
  44. var responseType = returnMarker != null ?
  45. GetGenericArguments(returnMarker)[0]
  46. : mi.ReturnType != typeof(object) && mi.ReturnType != typeof(void) ?
  47. mi.ReturnType
  48. : Type.GetType(requestType.FullName + "Response");
  49. RegisterRestPaths(appHost, requestType);
  50. appHost.AddServiceInfo(serviceType, requestType, responseType);
  51. }
  52. }
  53. private static Type GetTypeWithGenericTypeDefinitionOf(Type type, Type genericTypeDefinition)
  54. {
  55. foreach (var t in type.GetTypeInfo().ImplementedInterfaces)
  56. {
  57. if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == genericTypeDefinition)
  58. {
  59. return t;
  60. }
  61. }
  62. var genericType = FirstGenericType(type);
  63. if (genericType != null && genericType.GetGenericTypeDefinition() == genericTypeDefinition)
  64. {
  65. return genericType;
  66. }
  67. return null;
  68. }
  69. public static Type FirstGenericType(Type type)
  70. {
  71. while (type != null)
  72. {
  73. if (type.GetTypeInfo().IsGenericType)
  74. return type;
  75. type = type.GetTypeInfo().BaseType;
  76. }
  77. return null;
  78. }
  79. public readonly Dictionary<string, List<RestPath>> RestPathMap = new Dictionary<string, List<RestPath>>(StringComparer.OrdinalIgnoreCase);
  80. public void RegisterRestPaths(HttpListenerHost appHost, Type requestType)
  81. {
  82. var attrs = appHost.GetRouteAttributes(requestType);
  83. foreach (RouteAttribute attr in attrs)
  84. {
  85. var restPath = new RestPath(appHost.CreateInstance, appHost.GetParseFn, requestType, attr.Path, attr.Verbs, attr.Summary, attr.Notes);
  86. if (!restPath.IsValid)
  87. throw new NotSupportedException(string.Format(
  88. "RestPath '{0}' on Type '{1}' is not Valid", attr.Path, requestType.GetMethodName()));
  89. RegisterRestPath(restPath);
  90. }
  91. }
  92. private static readonly char[] InvalidRouteChars = new[] { '?', '&' };
  93. public void RegisterRestPath(RestPath restPath)
  94. {
  95. if (!restPath.Path.StartsWith("/"))
  96. throw new ArgumentException(string.Format("Route '{0}' on '{1}' must start with a '/'", restPath.Path, restPath.RequestType.GetMethodName()));
  97. if (restPath.Path.IndexOfAny(InvalidRouteChars) != -1)
  98. throw new ArgumentException(string.Format("Route '{0}' on '{1}' contains invalid chars. " +
  99. "See https://github.com/ServiceStack/ServiceStack/wiki/Routing for info on valid routes.", restPath.Path, restPath.RequestType.GetMethodName()));
  100. List<RestPath> pathsAtFirstMatch;
  101. if (!RestPathMap.TryGetValue(restPath.FirstMatchHashKey, out pathsAtFirstMatch))
  102. {
  103. pathsAtFirstMatch = new List<RestPath>();
  104. RestPathMap[restPath.FirstMatchHashKey] = pathsAtFirstMatch;
  105. }
  106. pathsAtFirstMatch.Add(restPath);
  107. }
  108. public RestPath GetRestPathForRequest(string httpMethod, string pathInfo, ILogger logger)
  109. {
  110. var matchUsingPathParts = RestPath.GetPathPartsForMatching(pathInfo);
  111. List<RestPath> firstMatches;
  112. var yieldedHashMatches = RestPath.GetFirstMatchHashKeys(matchUsingPathParts);
  113. foreach (var potentialHashMatch in yieldedHashMatches)
  114. {
  115. if (!this.RestPathMap.TryGetValue(potentialHashMatch, out firstMatches))
  116. {
  117. continue;
  118. }
  119. var bestScore = -1;
  120. foreach (var restPath in firstMatches)
  121. {
  122. var score = restPath.MatchScore(httpMethod, matchUsingPathParts, logger);
  123. if (score > bestScore) bestScore = score;
  124. }
  125. if (bestScore > 0)
  126. {
  127. foreach (var restPath in firstMatches)
  128. {
  129. if (bestScore == restPath.MatchScore(httpMethod, matchUsingPathParts, logger))
  130. return restPath;
  131. }
  132. }
  133. }
  134. var yieldedWildcardMatches = RestPath.GetFirstMatchWildCardHashKeys(matchUsingPathParts);
  135. foreach (var potentialHashMatch in yieldedWildcardMatches)
  136. {
  137. if (!this.RestPathMap.TryGetValue(potentialHashMatch, out firstMatches)) continue;
  138. var bestScore = -1;
  139. foreach (var restPath in firstMatches)
  140. {
  141. var score = restPath.MatchScore(httpMethod, matchUsingPathParts, logger);
  142. if (score > bestScore) bestScore = score;
  143. }
  144. if (bestScore > 0)
  145. {
  146. foreach (var restPath in firstMatches)
  147. {
  148. if (bestScore == restPath.MatchScore(httpMethod, matchUsingPathParts, logger))
  149. return restPath;
  150. }
  151. }
  152. }
  153. return null;
  154. }
  155. public Task<object> Execute(HttpListenerHost appHost, object requestDto, IRequest req)
  156. {
  157. req.Dto = requestDto;
  158. var requestType = requestDto.GetType();
  159. req.OperationName = requestType.Name;
  160. var serviceType = appHost.GetServiceTypeByRequest(requestType);
  161. var service = appHost.CreateInstance(serviceType);
  162. //var service = typeFactory.CreateInstance(serviceType);
  163. var serviceRequiresContext = service as IRequiresRequest;
  164. if (serviceRequiresContext != null)
  165. {
  166. serviceRequiresContext.Request = req;
  167. }
  168. if (req.Dto == null) // Don't override existing batched DTO[]
  169. req.Dto = requestDto;
  170. //Executes the service and returns the result
  171. return ServiceExecGeneral.Execute(serviceType, req, service, requestDto, requestType.GetMethodName());
  172. }
  173. }
  174. }