ServiceExec.cs 7.2 KB

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