ServiceHandler.cs 8.9 KB

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