ServiceHandler.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Reflection;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Emby.Server.Implementations.HttpServer;
  8. using MediaBrowser.Model.Services;
  9. using Microsoft.AspNetCore.Http;
  10. using Microsoft.Extensions.Logging;
  11. namespace Emby.Server.Implementations.Services
  12. {
  13. public class ServiceHandler
  14. {
  15. private RestPath _restPath;
  16. private string _responseContentType;
  17. internal ServiceHandler(RestPath restPath, string responseContentType)
  18. {
  19. _restPath = restPath;
  20. _responseContentType = responseContentType;
  21. }
  22. protected static Task<object> CreateContentTypeRequest(HttpListenerHost host, IRequest httpReq, Type requestType, string contentType)
  23. {
  24. if (!string.IsNullOrEmpty(contentType) && httpReq.ContentLength > 0)
  25. {
  26. var deserializer = RequestHelper.GetRequestReader(host, contentType);
  27. if (deserializer != null)
  28. {
  29. return deserializer.Invoke(requestType, httpReq.InputStream);
  30. }
  31. }
  32. return Task.FromResult(host.CreateInstance(requestType));
  33. }
  34. public static string GetSanitizedPathInfo(string pathInfo, out string contentType)
  35. {
  36. contentType = null;
  37. var pos = pathInfo.LastIndexOf('.');
  38. if (pos != -1)
  39. {
  40. var format = pathInfo.Substring(pos + 1);
  41. contentType = GetFormatContentType(format);
  42. if (contentType != null)
  43. {
  44. pathInfo = pathInfo.Substring(0, pos);
  45. }
  46. }
  47. return pathInfo;
  48. }
  49. private static string GetFormatContentType(string format)
  50. {
  51. // built-in formats
  52. switch (format)
  53. {
  54. case "json": return "application/json";
  55. case "xml": return "application/xml";
  56. default: return null;
  57. }
  58. }
  59. public async Task ProcessRequestAsync(HttpListenerHost httpHost, IRequest httpReq, HttpResponse httpRes, ILogger logger, CancellationToken cancellationToken)
  60. {
  61. httpReq.Items["__route"] = _restPath;
  62. if (_responseContentType != null)
  63. {
  64. httpReq.ResponseContentType = _responseContentType;
  65. }
  66. var request = await CreateRequest(httpHost, httpReq, _restPath, logger).ConfigureAwait(false);
  67. httpHost.ApplyRequestFilters(httpReq, httpRes, request);
  68. var response = await httpHost.ServiceController.Execute(httpHost, request, httpReq).ConfigureAwait(false);
  69. // Apply response filters
  70. foreach (var responseFilter in httpHost.ResponseFilters)
  71. {
  72. responseFilter(httpReq, httpRes, response);
  73. }
  74. await ResponseHelper.WriteToResponse(httpRes, httpReq, response, cancellationToken).ConfigureAwait(false);
  75. }
  76. public static async Task<object> CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, ILogger logger)
  77. {
  78. var requestType = restPath.RequestType;
  79. if (RequireqRequestStream(requestType))
  80. {
  81. // Used by IRequiresRequestStream
  82. var requestParams = GetRequestParams(httpReq.Response.HttpContext.Request);
  83. var request = ServiceHandler.CreateRequest(httpReq, restPath, requestParams, host.CreateInstance(requestType));
  84. var rawReq = (IRequiresRequestStream)request;
  85. rawReq.RequestStream = httpReq.InputStream;
  86. return rawReq;
  87. }
  88. else
  89. {
  90. var requestParams = GetFlattenedRequestParams(httpReq.Response.HttpContext.Request);
  91. var requestDto = await CreateContentTypeRequest(host, httpReq, restPath.RequestType, httpReq.ContentType).ConfigureAwait(false);
  92. return CreateRequest(httpReq, restPath, requestParams, requestDto);
  93. }
  94. }
  95. public static bool RequireqRequestStream(Type requestType)
  96. {
  97. var requiresRequestStreamTypeInfo = typeof(IRequiresRequestStream).GetTypeInfo();
  98. return requiresRequestStreamTypeInfo.IsAssignableFrom(requestType.GetTypeInfo());
  99. }
  100. public static object CreateRequest(IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams, object requestDto)
  101. {
  102. var pathInfo = !restPath.IsWildCardPath
  103. ? GetSanitizedPathInfo(httpReq.PathInfo, out _)
  104. : httpReq.PathInfo;
  105. return restPath.CreateRequest(pathInfo, requestParams, requestDto);
  106. }
  107. /// <summary>
  108. /// Duplicate Params are given a unique key by appending a #1 suffix
  109. /// </summary>
  110. private static Dictionary<string, string> GetRequestParams(HttpRequest request)
  111. {
  112. var map = new Dictionary<string, string>();
  113. foreach (var pair in request.Query)
  114. {
  115. var values = pair.Value;
  116. if (values.Count == 1)
  117. {
  118. map[pair.Key] = values[0];
  119. }
  120. else
  121. {
  122. for (var i = 0; i < values.Count; i++)
  123. {
  124. map[pair.Key + (i == 0 ? string.Empty : "#" + i)] = values[i];
  125. }
  126. }
  127. }
  128. if ((IsMethod(request.Method, "POST") || IsMethod(request.Method, "PUT"))
  129. && request.HasFormContentType)
  130. {
  131. foreach (var pair in request.Form)
  132. {
  133. var values = pair.Value;
  134. if (values.Count == 1)
  135. {
  136. map[pair.Key] = values[0];
  137. }
  138. else
  139. {
  140. for (var i = 0; i < values.Count; i++)
  141. {
  142. map[pair.Key + (i == 0 ? string.Empty : "#" + i)] = values[i];
  143. }
  144. }
  145. }
  146. }
  147. return map;
  148. }
  149. private static bool IsMethod(string method, string expected)
  150. => string.Equals(method, expected, StringComparison.OrdinalIgnoreCase);
  151. /// <summary>
  152. /// Duplicate params have their values joined together in a comma-delimited string.
  153. /// </summary>
  154. private static Dictionary<string, string> GetFlattenedRequestParams(HttpRequest request)
  155. {
  156. var map = new Dictionary<string, string>();
  157. foreach (var pair in request.Query)
  158. {
  159. map[pair.Key] = pair.Value;
  160. }
  161. if ((IsMethod(request.Method, "POST") || IsMethod(request.Method, "PUT"))
  162. && request.HasFormContentType)
  163. {
  164. foreach (var pair in request.Form)
  165. {
  166. map[pair.Key] = pair.Value;
  167. }
  168. }
  169. return map;
  170. }
  171. }
  172. }