ServiceExec.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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 async 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) return null;
  72. }
  73. }
  74. var response = actionContext.ServiceAction(instance, requestDto);
  75. var taskResponse = response as Task;
  76. if (taskResponse != null)
  77. {
  78. await taskResponse.ConfigureAwait(false);
  79. response = ServiceHandler.GetTaskResult(taskResponse);
  80. }
  81. return response;
  82. }
  83. var expectedMethodName = actionName.Substring(0, 1) + actionName.Substring(1).ToLower();
  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. public static List<ServiceMethod> Reset(Type serviceType)
  87. {
  88. var actions = new List<ServiceMethod>();
  89. foreach (var mi in serviceType.GetActions())
  90. {
  91. var actionName = mi.Name;
  92. var args = mi.GetParameters();
  93. var requestType = args[0].ParameterType;
  94. var actionCtx = new ServiceMethod
  95. {
  96. Id = ServiceMethod.Key(serviceType, actionName, requestType.GetMethodName())
  97. };
  98. try
  99. {
  100. actionCtx.ServiceAction = CreateExecFn(serviceType, requestType, mi);
  101. }
  102. catch
  103. {
  104. //Potential problems with MONO, using reflection for fallback
  105. actionCtx.ServiceAction = (service, request) =>
  106. mi.Invoke(service, new[] { request });
  107. }
  108. var reqFilters = new List<IHasRequestFilter>();
  109. foreach (var attr in mi.GetCustomAttributes(true))
  110. {
  111. var hasReqFilter = attr as IHasRequestFilter;
  112. if (hasReqFilter != null)
  113. reqFilters.Add(hasReqFilter);
  114. }
  115. if (reqFilters.Count > 0)
  116. actionCtx.RequestFilters = reqFilters.OrderBy(i => i.Priority).ToArray(reqFilters.Count);
  117. actions.Add(actionCtx);
  118. }
  119. return actions;
  120. }
  121. private static ActionInvokerFn CreateExecFn(Type serviceType, Type requestType, MethodInfo mi)
  122. {
  123. var serviceParam = Expression.Parameter(typeof(object), "serviceObj");
  124. var serviceStrong = Expression.Convert(serviceParam, serviceType);
  125. var requestDtoParam = Expression.Parameter(typeof(object), "requestDto");
  126. var requestDtoStrong = Expression.Convert(requestDtoParam, requestType);
  127. Expression callExecute = Expression.Call(
  128. serviceStrong, mi, requestDtoStrong);
  129. if (mi.ReturnType != typeof(void))
  130. {
  131. var executeFunc = Expression.Lambda<ActionInvokerFn>
  132. (callExecute, serviceParam, requestDtoParam).Compile();
  133. return executeFunc;
  134. }
  135. else
  136. {
  137. var executeFunc = Expression.Lambda<VoidActionInvokerFn>
  138. (callExecute, serviceParam, requestDtoParam).Compile();
  139. return (service, request) =>
  140. {
  141. executeFunc(service, request);
  142. return null;
  143. };
  144. }
  145. }
  146. }
  147. }