ServiceHandler.cs 8.4 KB

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