ServiceHandler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. var request = ServiceHandler.CreateRequest(httpReq, restPath, GetRequestParams(httpReq), host.CreateInstance(requestType));
  135. var rawReq = (IRequiresRequestStream)request;
  136. rawReq.RequestStream = httpReq.InputStream;
  137. return rawReq;
  138. }
  139. var requestParams = GetFlattenedRequestParams(httpReq);
  140. return CreateRequest(host, httpReq, restPath, requestParams);
  141. }
  142. private static bool RequireqRequestStream(Type requestType)
  143. {
  144. var requiresRequestStreamTypeInfo = typeof(IRequiresRequestStream).GetTypeInfo();
  145. return requiresRequestStreamTypeInfo.IsAssignableFrom(requestType.GetTypeInfo());
  146. }
  147. public static object CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams)
  148. {
  149. var requestDto = CreateContentTypeRequest(host, httpReq, restPath.RequestType, httpReq.ContentType);
  150. return CreateRequest(httpReq, restPath, requestParams, requestDto);
  151. }
  152. public static object CreateRequest(IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams, object requestDto)
  153. {
  154. string contentType;
  155. var pathInfo = !restPath.IsWildCardPath
  156. ? GetSanitizedPathInfo(httpReq.PathInfo, out contentType)
  157. : httpReq.PathInfo;
  158. return restPath.CreateRequest(pathInfo, requestParams, requestDto);
  159. }
  160. /// <summary>
  161. /// Duplicate Params are given a unique key by appending a #1 suffix
  162. /// </summary>
  163. private static Dictionary<string, string> GetRequestParams(IRequest request)
  164. {
  165. var map = new Dictionary<string, string>();
  166. foreach (var name in request.QueryString.Keys)
  167. {
  168. if (name == null) continue; //thank you ASP.NET
  169. var values = request.QueryString.GetValues(name);
  170. if (values.Count == 1)
  171. {
  172. map[name] = values[0];
  173. }
  174. else
  175. {
  176. for (var i = 0; i < values.Count; i++)
  177. {
  178. map[name + (i == 0 ? "" : "#" + i)] = values[i];
  179. }
  180. }
  181. }
  182. if ((IsMethod(request.Verb, "POST") || IsMethod(request.Verb, "PUT")))
  183. {
  184. var formData = request.FormData;
  185. if (formData != null)
  186. {
  187. foreach (var name in formData.Keys)
  188. {
  189. if (name == null) continue; //thank you ASP.NET
  190. var values = formData.GetValues(name);
  191. if (values.Count == 1)
  192. {
  193. map[name] = values[0];
  194. }
  195. else
  196. {
  197. for (var i = 0; i < values.Count; i++)
  198. {
  199. map[name + (i == 0 ? "" : "#" + i)] = values[i];
  200. }
  201. }
  202. }
  203. }
  204. }
  205. return map;
  206. }
  207. private static bool IsMethod(string method, string expected)
  208. {
  209. return string.Equals(method, expected, StringComparison.OrdinalIgnoreCase);
  210. }
  211. /// <summary>
  212. /// Duplicate params have their values joined together in a comma-delimited string
  213. /// </summary>
  214. private static Dictionary<string, string> GetFlattenedRequestParams(IRequest request)
  215. {
  216. var map = new Dictionary<string, string>();
  217. foreach (var name in request.QueryString.Keys)
  218. {
  219. if (name == null) continue; //thank you ASP.NET
  220. map[name] = request.QueryString[name];
  221. }
  222. if ((IsMethod(request.Verb, "POST") || IsMethod(request.Verb, "PUT")))
  223. {
  224. var formData = request.FormData;
  225. if (formData != null)
  226. {
  227. foreach (var name in formData.Keys)
  228. {
  229. if (name == null) continue; //thank you ASP.NET
  230. map[name] = formData[name];
  231. }
  232. }
  233. }
  234. return map;
  235. }
  236. private static void SetRoute(IRequest req, RestPath route)
  237. {
  238. req.Items["__route"] = route;
  239. }
  240. private static RestPath GetRoute(IRequest req)
  241. {
  242. object route;
  243. req.Items.TryGetValue("__route", out route);
  244. return route as RestPath;
  245. }
  246. }
  247. }