ServiceHandler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Threading.Tasks;
  5. using Emby.Server.Implementations.HttpServer;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Services;
  8. namespace Emby.Server.Implementations.Services
  9. {
  10. public class ServiceHandler
  11. {
  12. public async Task<object> HandleResponseAsync(object response)
  13. {
  14. var taskResponse = response as Task;
  15. if (taskResponse == null)
  16. {
  17. return response;
  18. }
  19. await taskResponse.ConfigureAwait(false);
  20. var taskResult = GetTaskResult(taskResponse);
  21. var subTask = taskResult as Task;
  22. if (subTask != null)
  23. {
  24. taskResult = GetTaskResult(subTask);
  25. }
  26. return taskResult;
  27. }
  28. internal static object GetTaskResult(Task task)
  29. {
  30. try
  31. {
  32. var taskObject = task as Task<object>;
  33. if (taskObject != null)
  34. {
  35. return taskObject.Result;
  36. }
  37. task.Wait();
  38. var type = task.GetType().GetTypeInfo();
  39. if (!type.IsGenericType)
  40. {
  41. return null;
  42. }
  43. return type.GetDeclaredProperty("Result").GetValue(task);
  44. }
  45. catch (TypeAccessException)
  46. {
  47. return null; //return null for void Task's
  48. }
  49. }
  50. protected static object CreateContentTypeRequest(HttpListenerHost host, IRequest httpReq, Type requestType, string contentType)
  51. {
  52. if (!string.IsNullOrEmpty(contentType) && httpReq.ContentLength > 0)
  53. {
  54. var deserializer = RequestHelper.GetRequestReader(host, contentType);
  55. if (deserializer != null)
  56. {
  57. return deserializer(requestType, httpReq.InputStream);
  58. }
  59. }
  60. return host.CreateInstance(requestType);
  61. }
  62. public static RestPath FindMatchingRestPath(string httpMethod, string pathInfo, ILogger logger, out string contentType)
  63. {
  64. pathInfo = GetSanitizedPathInfo(pathInfo, out contentType);
  65. return ServiceController.Instance.GetRestPathForRequest(httpMethod, pathInfo, logger);
  66. }
  67. public static string GetSanitizedPathInfo(string pathInfo, out string contentType)
  68. {
  69. contentType = null;
  70. var pos = pathInfo.LastIndexOf('.');
  71. if (pos >= 0)
  72. {
  73. var format = pathInfo.Substring(pos + 1);
  74. contentType = GetFormatContentType(format);
  75. if (contentType != null)
  76. {
  77. pathInfo = pathInfo.Substring(0, pos);
  78. }
  79. }
  80. return pathInfo;
  81. }
  82. private static string GetFormatContentType(string format)
  83. {
  84. //built-in formats
  85. if (format == "json")
  86. return "application/json";
  87. if (format == "xml")
  88. return "application/xml";
  89. return null;
  90. }
  91. public RestPath GetRestPath(string httpMethod, string pathInfo)
  92. {
  93. if (this.RestPath == null)
  94. {
  95. string contentType;
  96. this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, new NullLogger(), out contentType);
  97. if (contentType != null)
  98. ResponseContentType = contentType;
  99. }
  100. return this.RestPath;
  101. }
  102. public RestPath RestPath { get; set; }
  103. // Set from SSHHF.GetHandlerForPathInfo()
  104. public string ResponseContentType { get; set; }
  105. public async Task ProcessRequestAsync(HttpListenerHost appHost, IRequest httpReq, IResponse httpRes, ILogger logger, string operationName)
  106. {
  107. var restPath = GetRestPath(httpReq.Verb, httpReq.PathInfo);
  108. if (restPath == null)
  109. {
  110. throw new NotSupportedException("No RestPath found for: " + httpReq.Verb + " " + httpReq.PathInfo);
  111. }
  112. SetRoute(httpReq, restPath);
  113. if (ResponseContentType != null)
  114. httpReq.ResponseContentType = ResponseContentType;
  115. var request = httpReq.Dto = CreateRequest(appHost, httpReq, restPath, logger);
  116. appHost.ApplyRequestFilters(httpReq, httpRes, request);
  117. var rawResponse = await appHost.ServiceController.Execute(appHost, request, httpReq).ConfigureAwait(false);
  118. var response = await HandleResponseAsync(rawResponse).ConfigureAwait(false);
  119. // Apply response filters
  120. foreach (var responseFilter in appHost.ResponseFilters)
  121. {
  122. responseFilter(httpReq, httpRes, response);
  123. }
  124. await ResponseHelper.WriteToResponse(httpRes, httpReq, response).ConfigureAwait(false);
  125. }
  126. public static object CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, ILogger logger)
  127. {
  128. var requestType = restPath.RequestType;
  129. if (RequireqRequestStream(requestType))
  130. {
  131. // Used by IRequiresRequestStream
  132. return CreateRequiresRequestStreamRequest(host, httpReq, requestType);
  133. }
  134. var requestParams = GetFlattenedRequestParams(httpReq);
  135. return CreateRequest(host, httpReq, restPath, requestParams);
  136. }
  137. private static bool RequireqRequestStream(Type requestType)
  138. {
  139. var requiresRequestStreamTypeInfo = typeof(IRequiresRequestStream).GetTypeInfo();
  140. return requiresRequestStreamTypeInfo.IsAssignableFrom(requestType.GetTypeInfo());
  141. }
  142. private static IRequiresRequestStream CreateRequiresRequestStreamRequest(HttpListenerHost host, IRequest req, Type requestType)
  143. {
  144. var restPath = GetRoute(req);
  145. var request = ServiceHandler.CreateRequest(req, restPath, GetRequestParams(req), host.CreateInstance(requestType));
  146. var rawReq = (IRequiresRequestStream)request;
  147. rawReq.RequestStream = req.InputStream;
  148. return rawReq;
  149. }
  150. public static object CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams)
  151. {
  152. var requestDto = CreateContentTypeRequest(host, httpReq, restPath.RequestType, httpReq.ContentType);
  153. return CreateRequest(httpReq, restPath, requestParams, requestDto);
  154. }
  155. public static object CreateRequest(IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams, object requestDto)
  156. {
  157. string contentType;
  158. var pathInfo = !restPath.IsWildCardPath
  159. ? GetSanitizedPathInfo(httpReq.PathInfo, out contentType)
  160. : httpReq.PathInfo;
  161. return restPath.CreateRequest(pathInfo, requestParams, requestDto);
  162. }
  163. /// <summary>
  164. /// Duplicate Params are given a unique key by appending a #1 suffix
  165. /// </summary>
  166. private static Dictionary<string, string> GetRequestParams(IRequest request)
  167. {
  168. var map = new Dictionary<string, string>();
  169. foreach (var name in request.QueryString.Keys)
  170. {
  171. if (name == null) continue; //thank you ASP.NET
  172. var values = request.QueryString.GetValues(name);
  173. if (values.Length == 1)
  174. {
  175. map[name] = values[0];
  176. }
  177. else
  178. {
  179. for (var i = 0; i < values.Length; i++)
  180. {
  181. map[name + (i == 0 ? "" : "#" + i)] = values[i];
  182. }
  183. }
  184. }
  185. if ((IsMethod(request.Verb, "POST") || IsMethod(request.Verb, "PUT")) && request.FormData != null)
  186. {
  187. foreach (var name in request.FormData.Keys)
  188. {
  189. if (name == null) continue; //thank you ASP.NET
  190. var values = request.FormData.GetValues(name);
  191. if (values.Length == 1)
  192. {
  193. map[name] = values[0];
  194. }
  195. else
  196. {
  197. for (var i = 0; i < values.Length; i++)
  198. {
  199. map[name + (i == 0 ? "" : "#" + i)] = values[i];
  200. }
  201. }
  202. }
  203. }
  204. return map;
  205. }
  206. private static bool IsMethod(string method, string expected)
  207. {
  208. return string.Equals(method, expected, StringComparison.OrdinalIgnoreCase);
  209. }
  210. /// <summary>
  211. /// Duplicate params have their values joined together in a comma-delimited string
  212. /// </summary>
  213. private static Dictionary<string, string> GetFlattenedRequestParams(IRequest request)
  214. {
  215. var map = new Dictionary<string, string>();
  216. foreach (var name in request.QueryString.Keys)
  217. {
  218. if (name == null) continue; //thank you ASP.NET
  219. map[name] = request.QueryString[name];
  220. }
  221. if ((IsMethod(request.Verb, "POST") || IsMethod(request.Verb, "PUT")) && request.FormData != null)
  222. {
  223. foreach (var name in request.FormData.Keys)
  224. {
  225. if (name == null) continue; //thank you ASP.NET
  226. map[name] = request.FormData[name];
  227. }
  228. }
  229. return map;
  230. }
  231. private static void SetRoute(IRequest req, RestPath route)
  232. {
  233. req.Items["__route"] = route;
  234. }
  235. private static RestPath GetRoute(IRequest req)
  236. {
  237. object route;
  238. req.Items.TryGetValue("__route", out route);
  239. return route as RestPath;
  240. }
  241. }
  242. }