ServiceExec.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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 HashSet<string> AllVerbs = new HashSet<string>(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 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. public 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 async Task<object> Execute(Type serviceType, IRequest request, object instance, object requestDto, string requestName)
  60. {
  61. var actionName = request.Verb ?? "POST";
  62. ServiceMethod actionContext;
  63. if (ServiceExecGeneral.execMap.TryGetValue(ServiceMethod.Key(serviceType, actionName, requestName), out actionContext))
  64. {
  65. if (actionContext.RequestFilters != null)
  66. {
  67. foreach (var requestFilter in actionContext.RequestFilters)
  68. {
  69. requestFilter.RequestFilter(request, request.Response, requestDto);
  70. if (request.Response.IsClosed) return null;
  71. }
  72. }
  73. var response = actionContext.ServiceAction(instance, requestDto);
  74. var taskResponse = response as Task;
  75. if (taskResponse != null)
  76. {
  77. await taskResponse.ConfigureAwait(false);
  78. response = ServiceHandler.GetTaskResult(taskResponse);
  79. }
  80. return response;
  81. }
  82. var expectedMethodName = actionName.Substring(0, 1) + actionName.Substring(1).ToLower();
  83. throw new NotImplementedException(string.Format("Could not find method named {1}({0}) or Any({0}) on Service {2}", requestDto.GetType().GetMethodName(), expectedMethodName, serviceType.GetMethodName()));
  84. }
  85. public static List<ServiceMethod> Reset(Type serviceType)
  86. {
  87. var actions = new List<ServiceMethod>();
  88. foreach (var mi in serviceType.GetActions())
  89. {
  90. var actionName = mi.Name;
  91. var args = mi.GetParameters();
  92. var requestType = args[0].ParameterType;
  93. var actionCtx = new ServiceMethod
  94. {
  95. Id = ServiceMethod.Key(serviceType, actionName, requestType.GetMethodName())
  96. };
  97. try
  98. {
  99. actionCtx.ServiceAction = CreateExecFn(serviceType, requestType, mi);
  100. }
  101. catch
  102. {
  103. //Potential problems with MONO, using reflection for fallback
  104. actionCtx.ServiceAction = (service, request) =>
  105. mi.Invoke(service, new[] { request });
  106. }
  107. var reqFilters = new List<IHasRequestFilter>();
  108. foreach (var attr in mi.GetCustomAttributes(true))
  109. {
  110. var hasReqFilter = attr as IHasRequestFilter;
  111. if (hasReqFilter != null)
  112. reqFilters.Add(hasReqFilter);
  113. }
  114. if (reqFilters.Count > 0)
  115. actionCtx.RequestFilters = reqFilters.OrderBy(i => i.Priority).ToArray(reqFilters.Count);
  116. actions.Add(actionCtx);
  117. }
  118. return actions;
  119. }
  120. private static ActionInvokerFn CreateExecFn(Type serviceType, Type requestType, MethodInfo mi)
  121. {
  122. var serviceParam = Expression.Parameter(typeof(object), "serviceObj");
  123. var serviceStrong = Expression.Convert(serviceParam, serviceType);
  124. var requestDtoParam = Expression.Parameter(typeof(object), "requestDto");
  125. var requestDtoStrong = Expression.Convert(requestDtoParam, requestType);
  126. Expression callExecute = Expression.Call(
  127. serviceStrong, mi, requestDtoStrong);
  128. if (mi.ReturnType != typeof(void))
  129. {
  130. var executeFunc = Expression.Lambda<ActionInvokerFn>
  131. (callExecute, serviceParam, requestDtoParam).Compile();
  132. return executeFunc;
  133. }
  134. else
  135. {
  136. var executeFunc = Expression.Lambda<VoidActionInvokerFn>
  137. (callExecute, serviceParam, requestDtoParam).Compile();
  138. return (service, request) =>
  139. {
  140. executeFunc(service, request);
  141. return null;
  142. };
  143. }
  144. }
  145. }
  146. }