2
0

ServiceExec.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Model.Services;
  9. namespace Emby.Server.Implementations.Services
  10. {
  11. public static class ServiceExecExtensions
  12. {
  13. public static string[] AllVerbs = new[] {
  14. "OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", // RFC 2616
  15. "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "MOVE", "LOCK", "UNLOCK", // RFC 2518
  16. "VERSION-CONTROL", "REPORT", "CHECKOUT", "CHECKIN", "UNCHECKOUT",
  17. "MKWORKSPACE", "UPDATE", "LABEL", "MERGE", "BASELINE-CONTROL", "MKACTIVITY", // RFC 3253
  18. "ORDERPATCH", // RFC 3648
  19. "ACL", // RFC 3744
  20. "PATCH", // https://datatracker.ietf.org/doc/draft-dusseault-http-patch/
  21. "SEARCH", // https://datatracker.ietf.org/doc/draft-reschke-webdav-search/
  22. "BCOPY", "BDELETE", "BMOVE", "BPROPFIND", "BPROPPATCH", "NOTIFY",
  23. "POLL", "SUBSCRIBE", "UNSUBSCRIBE"
  24. };
  25. public static List<MethodInfo> GetActions(this Type serviceType)
  26. {
  27. var list = new List<MethodInfo>();
  28. foreach (var mi in serviceType.GetRuntimeMethods())
  29. {
  30. if (!mi.IsPublic)
  31. {
  32. continue;
  33. }
  34. if (mi.IsStatic)
  35. {
  36. continue;
  37. }
  38. if (mi.GetParameters().Length != 1)
  39. {
  40. continue;
  41. }
  42. var actionName = mi.Name;
  43. if (!AllVerbs.Contains(actionName, StringComparer.OrdinalIgnoreCase))
  44. {
  45. continue;
  46. }
  47. list.Add(mi);
  48. }
  49. return list;
  50. }
  51. }
  52. internal static class ServiceExecGeneral
  53. {
  54. private static Dictionary<string, ServiceMethod> execMap = new Dictionary<string, ServiceMethod>();
  55. public static void CreateServiceRunnersFor(Type requestType, List<ServiceMethod> actions)
  56. {
  57. foreach (var actionCtx in actions)
  58. {
  59. if (execMap.ContainsKey(actionCtx.Id))
  60. {
  61. continue;
  62. }
  63. execMap[actionCtx.Id] = actionCtx;
  64. }
  65. }
  66. public static Task<object> Execute(Type serviceType, IRequest request, object instance, object requestDto, string requestName)
  67. {
  68. var actionName = request.Verb ?? "POST";
  69. if (execMap.TryGetValue(ServiceMethod.Key(serviceType, actionName, requestName), out ServiceMethod actionContext))
  70. {
  71. if (actionContext.RequestFilters != null)
  72. {
  73. foreach (var requestFilter in actionContext.RequestFilters)
  74. {
  75. requestFilter.RequestFilter(request, request.Response, requestDto);
  76. if (request.Response.HasStarted)
  77. {
  78. Task.FromResult<object>(null);
  79. }
  80. }
  81. }
  82. var response = actionContext.ServiceAction(instance, requestDto);
  83. if (response is Task taskResponse)
  84. {
  85. return GetTaskResult(taskResponse);
  86. }
  87. return Task.FromResult(response);
  88. }
  89. var expectedMethodName = actionName.Substring(0, 1) + actionName.Substring(1).ToLowerInvariant();
  90. throw new NotImplementedException(string.Format("Could not find method named {1}({0}) or Any({0}) on Service {2}", requestDto.GetType().GetMethodName(), expectedMethodName, serviceType.GetMethodName()));
  91. }
  92. private static async Task<object> GetTaskResult(Task task)
  93. {
  94. try
  95. {
  96. if (task is Task<object> taskObject)
  97. {
  98. return await taskObject.ConfigureAwait(false);
  99. }
  100. await task.ConfigureAwait(false);
  101. var type = task.GetType().GetTypeInfo();
  102. if (!type.IsGenericType)
  103. {
  104. return null;
  105. }
  106. var resultProperty = type.GetDeclaredProperty("Result");
  107. if (resultProperty == null)
  108. {
  109. return null;
  110. }
  111. var result = resultProperty.GetValue(task);
  112. // hack alert
  113. if (result.GetType().Name.IndexOf("voidtaskresult", StringComparison.OrdinalIgnoreCase) != -1)
  114. {
  115. return null;
  116. }
  117. return result;
  118. }
  119. catch (TypeAccessException)
  120. {
  121. return null; // return null for void Task's
  122. }
  123. }
  124. public static List<ServiceMethod> Reset(Type serviceType)
  125. {
  126. var actions = new List<ServiceMethod>();
  127. foreach (var mi in serviceType.GetActions())
  128. {
  129. var actionName = mi.Name;
  130. var args = mi.GetParameters();
  131. var requestType = args[0].ParameterType;
  132. var actionCtx = new ServiceMethod
  133. {
  134. Id = ServiceMethod.Key(serviceType, actionName, requestType.GetMethodName())
  135. };
  136. actionCtx.ServiceAction = CreateExecFn(serviceType, requestType, mi);
  137. var reqFilters = new List<IHasRequestFilter>();
  138. foreach (var attr in mi.GetCustomAttributes(true))
  139. {
  140. if (attr is IHasRequestFilter hasReqFilter)
  141. {
  142. reqFilters.Add(hasReqFilter);
  143. }
  144. }
  145. if (reqFilters.Count > 0)
  146. {
  147. actionCtx.RequestFilters = reqFilters.OrderBy(i => i.Priority).ToArray();
  148. }
  149. actions.Add(actionCtx);
  150. }
  151. return actions;
  152. }
  153. private static ActionInvokerFn CreateExecFn(Type serviceType, Type requestType, MethodInfo mi)
  154. {
  155. var serviceParam = Expression.Parameter(typeof(object), "serviceObj");
  156. var serviceStrong = Expression.Convert(serviceParam, serviceType);
  157. var requestDtoParam = Expression.Parameter(typeof(object), "requestDto");
  158. var requestDtoStrong = Expression.Convert(requestDtoParam, requestType);
  159. Expression callExecute = Expression.Call(
  160. serviceStrong, mi, requestDtoStrong);
  161. if (mi.ReturnType != typeof(void))
  162. {
  163. var executeFunc = Expression.Lambda<ActionInvokerFn>(
  164. callExecute,
  165. serviceParam,
  166. requestDtoParam).Compile();
  167. return executeFunc;
  168. }
  169. else
  170. {
  171. var executeFunc = Expression.Lambda<VoidActionInvokerFn>(
  172. callExecute,
  173. serviceParam,
  174. requestDtoParam).Compile();
  175. return (service, request) =>
  176. {
  177. executeFunc(service, request);
  178. return null;
  179. };
  180. }
  181. }
  182. }
  183. }