ServiceHandler.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. 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, out string contentType)
  26. {
  27. pathInfo = GetSanitizedPathInfo(pathInfo, out contentType);
  28. return ServiceController.Instance.GetRestPathForRequest(httpMethod, pathInfo);
  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. this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, out string contentType);
  59. if (contentType != null)
  60. ResponseContentType = contentType;
  61. }
  62. return this.RestPath;
  63. }
  64. public RestPath RestPath { get; set; }
  65. // Set from SSHHF.GetHandlerForPathInfo()
  66. public string ResponseContentType { get; set; }
  67. public async Task ProcessRequestAsync(HttpListenerHost appHost, IRequest httpReq, IResponse httpRes, ILogger logger, string operationName, CancellationToken cancellationToken)
  68. {
  69. var restPath = GetRestPath(httpReq.Verb, httpReq.PathInfo);
  70. if (restPath == null)
  71. {
  72. throw new NotSupportedException("No RestPath found for: " + httpReq.Verb + " " + httpReq.PathInfo);
  73. }
  74. SetRoute(httpReq, restPath);
  75. if (ResponseContentType != null)
  76. httpReq.ResponseContentType = ResponseContentType;
  77. var request = httpReq.Dto = await CreateRequest(appHost, httpReq, restPath, logger).ConfigureAwait(false);
  78. appHost.ApplyRequestFilters(httpReq, httpRes, request);
  79. var response = await appHost.ServiceController.Execute(appHost, request, httpReq).ConfigureAwait(false);
  80. // Apply response filters
  81. foreach (var responseFilter in appHost.ResponseFilters)
  82. {
  83. responseFilter(httpReq, httpRes, response);
  84. }
  85. await ResponseHelper.WriteToResponse(httpRes, httpReq, response, cancellationToken).ConfigureAwait(false);
  86. }
  87. public static async Task<object> CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, ILogger logger)
  88. {
  89. var requestType = restPath.RequestType;
  90. if (RequireqRequestStream(requestType))
  91. {
  92. // Used by IRequiresRequestStream
  93. var requestParams = await GetRequestParams(httpReq).ConfigureAwait(false);
  94. var request = ServiceHandler.CreateRequest(httpReq, restPath, requestParams, host.CreateInstance(requestType));
  95. var rawReq = (IRequiresRequestStream)request;
  96. rawReq.RequestStream = httpReq.InputStream;
  97. return rawReq;
  98. }
  99. else
  100. {
  101. var requestParams = await GetFlattenedRequestParams(httpReq).ConfigureAwait(false);
  102. var requestDto = await CreateContentTypeRequest(host, httpReq, restPath.RequestType, httpReq.ContentType).ConfigureAwait(false);
  103. return CreateRequest(httpReq, restPath, requestParams, requestDto);
  104. }
  105. }
  106. public static bool RequireqRequestStream(Type requestType)
  107. {
  108. var requiresRequestStreamTypeInfo = typeof(IRequiresRequestStream).GetTypeInfo();
  109. return requiresRequestStreamTypeInfo.IsAssignableFrom(requestType.GetTypeInfo());
  110. }
  111. public static object CreateRequest(IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams, object requestDto)
  112. {
  113. var pathInfo = !restPath.IsWildCardPath
  114. ? GetSanitizedPathInfo(httpReq.PathInfo, out string contentType)
  115. : httpReq.PathInfo;
  116. return restPath.CreateRequest(pathInfo, requestParams, requestDto);
  117. }
  118. /// <summary>
  119. /// Duplicate Params are given a unique key by appending a #1 suffix
  120. /// </summary>
  121. private static async Task<Dictionary<string, string>> GetRequestParams(IRequest request)
  122. {
  123. var map = new Dictionary<string, string>();
  124. foreach (var name in request.QueryString.Keys)
  125. {
  126. if (name == null) continue; //thank you ASP.NET
  127. var values = request.QueryString.GetValues(name);
  128. if (values.Count == 1)
  129. {
  130. map[name] = values[0];
  131. }
  132. else
  133. {
  134. for (var i = 0; i < values.Count; i++)
  135. {
  136. map[name + (i == 0 ? "" : "#" + i)] = values[i];
  137. }
  138. }
  139. }
  140. if ((IsMethod(request.Verb, "POST") || IsMethod(request.Verb, "PUT")))
  141. {
  142. var formData = await request.GetFormData().ConfigureAwait(false);
  143. if (formData != null)
  144. {
  145. foreach (var name in formData.Keys)
  146. {
  147. if (name == null) continue; //thank you ASP.NET
  148. var values = formData.GetValues(name);
  149. if (values.Count == 1)
  150. {
  151. map[name] = values[0];
  152. }
  153. else
  154. {
  155. for (var i = 0; i < values.Count; i++)
  156. {
  157. map[name + (i == 0 ? "" : "#" + i)] = values[i];
  158. }
  159. }
  160. }
  161. }
  162. }
  163. return map;
  164. }
  165. private static bool IsMethod(string method, string expected)
  166. {
  167. return string.Equals(method, expected, StringComparison.OrdinalIgnoreCase);
  168. }
  169. /// <summary>
  170. /// Duplicate params have their values joined together in a comma-delimited string
  171. /// </summary>
  172. private static async Task<Dictionary<string, string>> GetFlattenedRequestParams(IRequest request)
  173. {
  174. var map = new Dictionary<string, string>();
  175. foreach (var name in request.QueryString.Keys)
  176. {
  177. if (name == null) continue; //thank you ASP.NET
  178. map[name] = request.QueryString[name];
  179. }
  180. if ((IsMethod(request.Verb, "POST") || IsMethod(request.Verb, "PUT")))
  181. {
  182. var formData = await request.GetFormData().ConfigureAwait(false);
  183. if (formData != null)
  184. {
  185. foreach (var name in formData.Keys)
  186. {
  187. if (name == null) continue; //thank you ASP.NET
  188. map[name] = formData[name];
  189. }
  190. }
  191. }
  192. return map;
  193. }
  194. private static void SetRoute(IRequest req, RestPath route)
  195. {
  196. req.Items["__route"] = route;
  197. }
  198. private static RestPath GetRoute(IRequest req)
  199. {
  200. req.Items.TryGetValue("__route", out var route);
  201. return route as RestPath;
  202. }
  203. }
  204. }