2
0

ServiceHandler.cs 8.8 KB

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