ServiceHandler.cs 7.2 KB

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