ServiceHandler.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. httpRes.HttpContext.SetServiceStackRequest(httpReq);
  69. var response = await httpHost.ServiceController.Execute(httpHost, request, httpReq).ConfigureAwait(false);
  70. // Apply response filters
  71. foreach (var responseFilter in httpHost.ResponseFilters)
  72. {
  73. responseFilter(httpReq, httpRes, response);
  74. }
  75. await ResponseHelper.WriteToResponse(httpRes, httpReq, response, cancellationToken).ConfigureAwait(false);
  76. }
  77. public static async Task<object> CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, ILogger logger)
  78. {
  79. var requestType = restPath.RequestType;
  80. if (RequireqRequestStream(requestType))
  81. {
  82. // Used by IRequiresRequestStream
  83. var requestParams = GetRequestParams(httpReq.Response.HttpContext.Request);
  84. var request = ServiceHandler.CreateRequest(httpReq, restPath, requestParams, host.CreateInstance(requestType));
  85. var rawReq = (IRequiresRequestStream)request;
  86. rawReq.RequestStream = httpReq.InputStream;
  87. return rawReq;
  88. }
  89. else
  90. {
  91. var requestParams = GetFlattenedRequestParams(httpReq.Response.HttpContext.Request);
  92. var requestDto = await CreateContentTypeRequest(host, httpReq, restPath.RequestType, httpReq.ContentType).ConfigureAwait(false);
  93. return CreateRequest(httpReq, restPath, requestParams, requestDto);
  94. }
  95. }
  96. public static bool RequireqRequestStream(Type requestType)
  97. {
  98. var requiresRequestStreamTypeInfo = typeof(IRequiresRequestStream).GetTypeInfo();
  99. return requiresRequestStreamTypeInfo.IsAssignableFrom(requestType.GetTypeInfo());
  100. }
  101. public static object CreateRequest(IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams, object requestDto)
  102. {
  103. var pathInfo = !restPath.IsWildCardPath
  104. ? GetSanitizedPathInfo(httpReq.PathInfo, out _)
  105. : httpReq.PathInfo;
  106. return restPath.CreateRequest(pathInfo, requestParams, requestDto);
  107. }
  108. /// <summary>
  109. /// Duplicate Params are given a unique key by appending a #1 suffix
  110. /// </summary>
  111. private static Dictionary<string, string> GetRequestParams(HttpRequest request)
  112. {
  113. var map = new Dictionary<string, string>();
  114. foreach (var pair in request.Query)
  115. {
  116. var values = pair.Value;
  117. if (values.Count == 1)
  118. {
  119. map[pair.Key] = values[0];
  120. }
  121. else
  122. {
  123. for (var i = 0; i < values.Count; i++)
  124. {
  125. map[pair.Key + (i == 0 ? string.Empty : "#" + i)] = values[i];
  126. }
  127. }
  128. }
  129. if ((IsMethod(request.Method, "POST") || IsMethod(request.Method, "PUT"))
  130. && request.HasFormContentType)
  131. {
  132. foreach (var pair in request.Form)
  133. {
  134. var values = pair.Value;
  135. if (values.Count == 1)
  136. {
  137. map[pair.Key] = values[0];
  138. }
  139. else
  140. {
  141. for (var i = 0; i < values.Count; i++)
  142. {
  143. map[pair.Key + (i == 0 ? string.Empty : "#" + i)] = values[i];
  144. }
  145. }
  146. }
  147. }
  148. return map;
  149. }
  150. private static bool IsMethod(string method, string expected)
  151. => string.Equals(method, expected, StringComparison.OrdinalIgnoreCase);
  152. /// <summary>
  153. /// Duplicate params have their values joined together in a comma-delimited string.
  154. /// </summary>
  155. private static Dictionary<string, string> GetFlattenedRequestParams(HttpRequest request)
  156. {
  157. var map = new Dictionary<string, string>();
  158. foreach (var pair in request.Query)
  159. {
  160. map[pair.Key] = pair.Value;
  161. }
  162. if ((IsMethod(request.Method, "POST") || IsMethod(request.Method, "PUT"))
  163. && request.HasFormContentType)
  164. {
  165. foreach (var pair in request.Form)
  166. {
  167. map[pair.Key] = pair.Value;
  168. }
  169. }
  170. return map;
  171. }
  172. }
  173. }