ServiceExec.cs 7.5 KB

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