ServiceExec.cs 7.7 KB

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