2
0

ServiceHandler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. // Apply response filters
  121. foreach (var responseFilter in appHost.ResponseFilters)
  122. {
  123. responseFilter(httpReq, httpRes, response);
  124. }
  125. await ResponseHelper.WriteToResponse(httpRes, httpReq, response, cancellationToken).ConfigureAwait(false);
  126. }
  127. public static object CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, ILogger logger)
  128. {
  129. var requestType = restPath.RequestType;
  130. if (RequireqRequestStream(requestType))
  131. {
  132. // Used by IRequiresRequestStream
  133. return CreateRequiresRequestStreamRequest(host, httpReq, requestType);
  134. }
  135. var requestParams = GetFlattenedRequestParams(httpReq);
  136. return CreateRequest(host, httpReq, restPath, requestParams);
  137. }
  138. private static bool RequireqRequestStream(Type requestType)
  139. {
  140. var requiresRequestStreamTypeInfo = typeof(IRequiresRequestStream).GetTypeInfo();
  141. return requiresRequestStreamTypeInfo.IsAssignableFrom(requestType.GetTypeInfo());
  142. }
  143. private static IRequiresRequestStream CreateRequiresRequestStreamRequest(HttpListenerHost host, IRequest req, Type requestType)
  144. {
  145. var restPath = GetRoute(req);
  146. var request = ServiceHandler.CreateRequest(req, restPath, GetRequestParams(req), host.CreateInstance(requestType));
  147. var rawReq = (IRequiresRequestStream)request;
  148. rawReq.RequestStream = req.InputStream;
  149. return rawReq;
  150. }
  151. public static object CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams)
  152. {
  153. var requestDto = CreateContentTypeRequest(host, httpReq, restPath.RequestType, httpReq.ContentType);
  154. return CreateRequest(httpReq, restPath, requestParams, requestDto);
  155. }
  156. public static object CreateRequest(IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams, object requestDto)
  157. {
  158. string contentType;
  159. var pathInfo = !restPath.IsWildCardPath
  160. ? GetSanitizedPathInfo(httpReq.PathInfo, out contentType)
  161. : httpReq.PathInfo;
  162. return restPath.CreateRequest(pathInfo, requestParams, requestDto);
  163. }
  164. /// <summary>
  165. /// Duplicate Params are given a unique key by appending a #1 suffix
  166. /// </summary>
  167. private static Dictionary<string, string> GetRequestParams(IRequest request)
  168. {
  169. var map = new Dictionary<string, string>();
  170. foreach (var name in request.QueryString.Keys)
  171. {
  172. if (name == null) continue; //thank you ASP.NET
  173. var values = request.QueryString.GetValues(name);
  174. if (values.Length == 1)
  175. {
  176. map[name] = values[0];
  177. }
  178. else
  179. {
  180. for (var i = 0; i < values.Length; i++)
  181. {
  182. map[name + (i == 0 ? "" : "#" + i)] = values[i];
  183. }
  184. }
  185. }
  186. if ((IsMethod(request.Verb, "POST") || IsMethod(request.Verb, "PUT")) && request.FormData != null)
  187. {
  188. foreach (var name in request.FormData.Keys)
  189. {
  190. if (name == null) continue; //thank you ASP.NET
  191. var values = request.FormData.GetValues(name);
  192. if (values.Length == 1)
  193. {
  194. map[name] = values[0];
  195. }
  196. else
  197. {
  198. for (var i = 0; i < values.Length; i++)
  199. {
  200. map[name + (i == 0 ? "" : "#" + i)] = values[i];
  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")) && request.FormData != null)
  223. {
  224. foreach (var name in request.FormData.Keys)
  225. {
  226. if (name == null) continue; //thank you ASP.NET
  227. map[name] = request.FormData[name];
  228. }
  229. }
  230. return map;
  231. }
  232. private static void SetRoute(IRequest req, RestPath route)
  233. {
  234. req.Items["__route"] = route;
  235. }
  236. private static RestPath GetRoute(IRequest req)
  237. {
  238. object route;
  239. req.Items.TryGetValue("__route", out route);
  240. return route as RestPath;
  241. }
  242. }
  243. }