ServiceExec.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 HashSet<string> AllVerbsSet = new HashSet<string>(AllVerbs);
  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. continue;
  40. var actionName = mi.Name;
  41. if (!AllVerbs.Contains(actionName, StringComparer.OrdinalIgnoreCase))
  42. continue;
  43. list.Add(mi);
  44. }
  45. return list;
  46. }
  47. }
  48. internal static class ServiceExecGeneral
  49. {
  50. private static Dictionary<string, ServiceMethod> execMap = new Dictionary<string, ServiceMethod>();
  51. public static void CreateServiceRunnersFor(Type requestType, List<ServiceMethod> actions)
  52. {
  53. foreach (var actionCtx in actions)
  54. {
  55. if (execMap.ContainsKey(actionCtx.Id)) continue;
  56. execMap[actionCtx.Id] = actionCtx;
  57. }
  58. }
  59. public static Task<object> Execute(Type serviceType, IRequest request, object instance, object requestDto, string requestName)
  60. {
  61. var actionName = request.Verb ?? "POST";
  62. if (execMap.TryGetValue(ServiceMethod.Key(serviceType, actionName, requestName), out ServiceMethod actionContext))
  63. {
  64. if (actionContext.RequestFilters != null)
  65. {
  66. foreach (var requestFilter in actionContext.RequestFilters)
  67. {
  68. requestFilter.RequestFilter(request, request.Response, requestDto);
  69. if (request.Response.IsClosed)
  70. {
  71. Task.FromResult<object>(null);
  72. }
  73. }
  74. }
  75. var response = actionContext.ServiceAction(instance, requestDto);
  76. var taskResponse = response as Task;
  77. if (taskResponse != null)
  78. {
  79. return GetTaskResult(taskResponse);
  80. }
  81. return Task.FromResult(response);
  82. }
  83. var expectedMethodName = actionName.Substring(0, 1) + actionName.Substring(1).ToLowerInvariant();
  84. throw new NotImplementedException(string.Format("Could not find method named {1}({0}) or Any({0}) on Service {2}", requestDto.GetType().GetMethodName(), expectedMethodName, serviceType.GetMethodName()));
  85. }
  86. private static async Task<object> GetTaskResult(Task task)
  87. {
  88. try
  89. {
  90. var taskObject = task as Task<object>;
  91. if (taskObject != null)
  92. {
  93. return await taskObject.ConfigureAwait(false);
  94. }
  95. await task.ConfigureAwait(false);
  96. var type = task.GetType().GetTypeInfo();
  97. if (!type.IsGenericType)
  98. {
  99. return null;
  100. }
  101. var resultProperty = type.GetDeclaredProperty("Result");
  102. if (resultProperty == null)
  103. {
  104. return null;
  105. }
  106. var result = resultProperty.GetValue(task);
  107. // hack alert
  108. if (result.GetType().Name.IndexOf("voidtaskresult", StringComparison.OrdinalIgnoreCase) != -1)
  109. {
  110. return null;
  111. }
  112. return result;
  113. }
  114. catch (TypeAccessException)
  115. {
  116. return null; //return null for void Task's
  117. }
  118. }
  119. public static List<ServiceMethod> Reset(Type serviceType)
  120. {
  121. var actions = new List<ServiceMethod>();
  122. foreach (var mi in serviceType.GetActions())
  123. {
  124. var actionName = mi.Name;
  125. var args = mi.GetParameters();
  126. var requestType = args[0].ParameterType;
  127. var actionCtx = new ServiceMethod
  128. {
  129. Id = ServiceMethod.Key(serviceType, actionName, requestType.GetMethodName())
  130. };
  131. try
  132. {
  133. actionCtx.ServiceAction = CreateExecFn(serviceType, requestType, mi);
  134. }
  135. catch
  136. {
  137. //Potential problems with MONO, using reflection for fallback
  138. actionCtx.ServiceAction = (service, request) =>
  139. mi.Invoke(service, new[] { request });
  140. }
  141. var reqFilters = new List<IHasRequestFilter>();
  142. foreach (var attr in mi.GetCustomAttributes(true))
  143. {
  144. var hasReqFilter = attr as IHasRequestFilter;
  145. if (hasReqFilter != null)
  146. reqFilters.Add(hasReqFilter);
  147. }
  148. if (reqFilters.Count > 0)
  149. actionCtx.RequestFilters = reqFilters.OrderBy(i => i.Priority).ToArray();
  150. actions.Add(actionCtx);
  151. }
  152. return actions;
  153. }
  154. private static ActionInvokerFn CreateExecFn(Type serviceType, Type requestType, MethodInfo mi)
  155. {
  156. var serviceParam = Expression.Parameter(typeof(object), "serviceObj");
  157. var serviceStrong = Expression.Convert(serviceParam, serviceType);
  158. var requestDtoParam = Expression.Parameter(typeof(object), "requestDto");
  159. var requestDtoStrong = Expression.Convert(requestDtoParam, requestType);
  160. Expression callExecute = Expression.Call(
  161. serviceStrong, mi, requestDtoStrong);
  162. if (mi.ReturnType != typeof(void))
  163. {
  164. var executeFunc = Expression.Lambda<ActionInvokerFn>
  165. (callExecute, serviceParam, requestDtoParam).Compile();
  166. return executeFunc;
  167. }
  168. else
  169. {
  170. var executeFunc = Expression.Lambda<VoidActionInvokerFn>
  171. (callExecute, serviceParam, requestDtoParam).Compile();
  172. return (service, request) =>
  173. {
  174. executeFunc(service, request);
  175. return null;
  176. };
  177. }
  178. }
  179. }
  180. }