ServiceHandler.cs 8.1 KB

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