ServiceHandler.cs 7.3 KB

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