ServiceHandler.cs 10 KB

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