ServiceHandler.cs 7.1 KB

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