ServiceExec.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 HashSet<string> AllVerbs = new HashSet<string>(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 IEnumerable<MethodInfo> GetActions(this Type serviceType)
  25. {
  26. foreach (var mi in serviceType.GetRuntimeMethods().Where(i => i.IsPublic && !i.IsStatic))
  27. {
  28. if (mi.GetParameters().Length != 1)
  29. continue;
  30. var actionName = mi.Name;
  31. if (!AllVerbs.Contains(actionName, StringComparer.OrdinalIgnoreCase) && !string.Equals(actionName, ServiceMethod.AnyAction, StringComparison.OrdinalIgnoreCase))
  32. continue;
  33. yield return mi;
  34. }
  35. }
  36. }
  37. internal static class ServiceExecGeneral
  38. {
  39. public static Dictionary<string, ServiceMethod> execMap = new Dictionary<string, ServiceMethod>();
  40. public static void CreateServiceRunnersFor(Type requestType, List<ServiceMethod> actions)
  41. {
  42. foreach (var actionCtx in actions)
  43. {
  44. if (execMap.ContainsKey(actionCtx.Id)) continue;
  45. execMap[actionCtx.Id] = actionCtx;
  46. }
  47. }
  48. public static async Task<object> Execute(Type serviceType, IRequest request, object instance, object requestDto, string requestName)
  49. {
  50. var actionName = request.Verb ?? "POST";
  51. ServiceMethod actionContext;
  52. if (ServiceExecGeneral.execMap.TryGetValue(ServiceMethod.Key(serviceType, actionName, requestName), out actionContext)
  53. || ServiceExecGeneral.execMap.TryGetValue(ServiceMethod.AnyKey(serviceType, requestName), out actionContext))
  54. {
  55. if (actionContext.RequestFilters != null)
  56. {
  57. foreach (var requestFilter in actionContext.RequestFilters)
  58. {
  59. requestFilter.RequestFilter(request, request.Response, requestDto);
  60. if (request.Response.IsClosed) return null;
  61. }
  62. }
  63. var response = actionContext.ServiceAction(instance, requestDto);
  64. var taskResponse = response as Task;
  65. if (taskResponse != null)
  66. {
  67. await taskResponse.ConfigureAwait(false);
  68. response = ServiceHandler.GetTaskResult(taskResponse);
  69. }
  70. return response;
  71. }
  72. var expectedMethodName = actionName.Substring(0, 1) + actionName.Substring(1).ToLower();
  73. throw new NotImplementedException(string.Format("Could not find method named {1}({0}) or Any({0}) on Service {2}", requestDto.GetType().GetMethodName(), expectedMethodName, serviceType.GetMethodName()));
  74. }
  75. public static List<ServiceMethod> Reset(Type serviceType)
  76. {
  77. var actions = new List<ServiceMethod>();
  78. foreach (var mi in serviceType.GetActions())
  79. {
  80. var actionName = mi.Name;
  81. var args = mi.GetParameters();
  82. var requestType = args[0].ParameterType;
  83. var actionCtx = new ServiceMethod
  84. {
  85. Id = ServiceMethod.Key(serviceType, actionName, requestType.GetMethodName())
  86. };
  87. try
  88. {
  89. actionCtx.ServiceAction = CreateExecFn(serviceType, requestType, mi);
  90. }
  91. catch
  92. {
  93. //Potential problems with MONO, using reflection for fallback
  94. actionCtx.ServiceAction = (service, request) =>
  95. mi.Invoke(service, new[] { request });
  96. }
  97. var reqFilters = new List<IHasRequestFilter>();
  98. foreach (var attr in mi.GetCustomAttributes(true))
  99. {
  100. var hasReqFilter = attr as IHasRequestFilter;
  101. if (hasReqFilter != null)
  102. reqFilters.Add(hasReqFilter);
  103. }
  104. if (reqFilters.Count > 0)
  105. actionCtx.RequestFilters = reqFilters.OrderBy(i => i.Priority).ToArray();
  106. actions.Add(actionCtx);
  107. }
  108. return actions;
  109. }
  110. private static ActionInvokerFn CreateExecFn(Type serviceType, Type requestType, MethodInfo mi)
  111. {
  112. var serviceParam = Expression.Parameter(typeof(object), "serviceObj");
  113. var serviceStrong = Expression.Convert(serviceParam, serviceType);
  114. var requestDtoParam = Expression.Parameter(typeof(object), "requestDto");
  115. var requestDtoStrong = Expression.Convert(requestDtoParam, requestType);
  116. Expression callExecute = Expression.Call(
  117. serviceStrong, mi, requestDtoStrong);
  118. if (mi.ReturnType != typeof(void))
  119. {
  120. var executeFunc = Expression.Lambda<ActionInvokerFn>
  121. (callExecute, serviceParam, requestDtoParam).Compile();
  122. return executeFunc;
  123. }
  124. else
  125. {
  126. var executeFunc = Expression.Lambda<VoidActionInvokerFn>
  127. (callExecute, serviceParam, requestDtoParam).Compile();
  128. return (service, request) =>
  129. {
  130. executeFunc(service, request);
  131. return null;
  132. };
  133. }
  134. }
  135. }
  136. }