HttpListenerHost.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Sockets;
  8. using System.Net.WebSockets;
  9. using System.Reflection;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Emby.Server.Implementations.Services;
  13. using Emby.Server.Implementations.SocketSharp;
  14. using MediaBrowser.Common.Extensions;
  15. using MediaBrowser.Common.Net;
  16. using MediaBrowser.Controller;
  17. using MediaBrowser.Controller.Authentication;
  18. using MediaBrowser.Controller.Configuration;
  19. using MediaBrowser.Controller.Net;
  20. using MediaBrowser.Model.Events;
  21. using MediaBrowser.Model.Globalization;
  22. using MediaBrowser.Model.Serialization;
  23. using MediaBrowser.Model.Services;
  24. using Microsoft.AspNetCore.Http;
  25. using Microsoft.AspNetCore.Http.Extensions;
  26. using Microsoft.AspNetCore.WebUtilities;
  27. using Microsoft.Extensions.Configuration;
  28. using Microsoft.Extensions.Hosting;
  29. using Microsoft.Extensions.Logging;
  30. using Microsoft.Extensions.Primitives;
  31. using ServiceStack.Text.Jsv;
  32. namespace Emby.Server.Implementations.HttpServer
  33. {
  34. public class HttpListenerHost : IHttpServer
  35. {
  36. /// <summary>
  37. /// The key for a setting that specifies the default redirect path
  38. /// to use for requests where the URL base prefix is invalid or missing.
  39. /// </summary>
  40. public const string DefaultRedirectKey = "HttpListenerHost:DefaultRedirectPath";
  41. private readonly ILogger _logger;
  42. private readonly ILoggerFactory _loggerFactory;
  43. private readonly IServerConfigurationManager _config;
  44. private readonly INetworkManager _networkManager;
  45. private readonly IServerApplicationHost _appHost;
  46. private readonly IJsonSerializer _jsonSerializer;
  47. private readonly IXmlSerializer _xmlSerializer;
  48. private readonly Func<Type, Func<string, object>> _funcParseFn;
  49. private readonly string _defaultRedirectPath;
  50. private readonly string _baseUrlPrefix;
  51. private readonly Dictionary<Type, Type> _serviceOperationsMap = new Dictionary<Type, Type>();
  52. private readonly IHostEnvironment _hostEnvironment;
  53. private IWebSocketListener[] _webSocketListeners = Array.Empty<IWebSocketListener>();
  54. private bool _disposed = false;
  55. public HttpListenerHost(
  56. IServerApplicationHost applicationHost,
  57. ILogger<HttpListenerHost> logger,
  58. IServerConfigurationManager config,
  59. IConfiguration configuration,
  60. INetworkManager networkManager,
  61. IJsonSerializer jsonSerializer,
  62. IXmlSerializer xmlSerializer,
  63. ILocalizationManager localizationManager,
  64. ServiceController serviceController,
  65. IHostEnvironment hostEnvironment,
  66. ILoggerFactory loggerFactory)
  67. {
  68. _appHost = applicationHost;
  69. _logger = logger;
  70. _config = config;
  71. _defaultRedirectPath = configuration[DefaultRedirectKey];
  72. _baseUrlPrefix = _config.Configuration.BaseUrl;
  73. _networkManager = networkManager;
  74. _jsonSerializer = jsonSerializer;
  75. _xmlSerializer = xmlSerializer;
  76. ServiceController = serviceController;
  77. _hostEnvironment = hostEnvironment;
  78. _loggerFactory = loggerFactory;
  79. _funcParseFn = t => s => JsvReader.GetParseFn(t)(s);
  80. Instance = this;
  81. ResponseFilters = Array.Empty<Action<IRequest, HttpResponse, object>>();
  82. GlobalResponse = localizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
  83. }
  84. public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
  85. public Action<IRequest, HttpResponse, object>[] ResponseFilters { get; set; }
  86. public static HttpListenerHost Instance { get; protected set; }
  87. public string[] UrlPrefixes { get; private set; }
  88. public string GlobalResponse { get; set; }
  89. public ServiceController ServiceController { get; }
  90. public object CreateInstance(Type type)
  91. {
  92. return _appHost.CreateInstance(type);
  93. }
  94. private static string NormalizeUrlPath(string path)
  95. {
  96. if (path.Length > 0 && path[0] == '/')
  97. {
  98. // If the path begins with a leading slash, just return it as-is
  99. return path;
  100. }
  101. else
  102. {
  103. // If the path does not begin with a leading slash, append one for consistency
  104. return "/" + path;
  105. }
  106. }
  107. /// <summary>
  108. /// Applies the request filters. Returns whether or not the request has been handled
  109. /// and no more processing should be done.
  110. /// </summary>
  111. /// <returns></returns>
  112. public void ApplyRequestFilters(IRequest req, HttpResponse res, object requestDto)
  113. {
  114. // Exec all RequestFilter attributes with Priority < 0
  115. var attributes = GetRequestFilterAttributes(requestDto.GetType());
  116. int count = attributes.Count;
  117. int i = 0;
  118. for (; i < count && attributes[i].Priority < 0; i++)
  119. {
  120. var attribute = attributes[i];
  121. attribute.RequestFilter(req, res, requestDto);
  122. }
  123. // Exec remaining RequestFilter attributes with Priority >= 0
  124. for (; i < count && attributes[i].Priority >= 0; i++)
  125. {
  126. var attribute = attributes[i];
  127. attribute.RequestFilter(req, res, requestDto);
  128. }
  129. }
  130. public Type GetServiceTypeByRequest(Type requestType)
  131. {
  132. _serviceOperationsMap.TryGetValue(requestType, out var serviceType);
  133. return serviceType;
  134. }
  135. public void AddServiceInfo(Type serviceType, Type requestType)
  136. {
  137. _serviceOperationsMap[requestType] = serviceType;
  138. }
  139. private List<IHasRequestFilter> GetRequestFilterAttributes(Type requestDtoType)
  140. {
  141. var attributes = requestDtoType.GetCustomAttributes(true).OfType<IHasRequestFilter>().ToList();
  142. var serviceType = GetServiceTypeByRequest(requestDtoType);
  143. if (serviceType != null)
  144. {
  145. attributes.AddRange(serviceType.GetCustomAttributes(true).OfType<IHasRequestFilter>());
  146. }
  147. attributes.Sort((x, y) => x.Priority - y.Priority);
  148. return attributes;
  149. }
  150. private static Exception GetActualException(Exception ex)
  151. {
  152. if (ex is AggregateException agg)
  153. {
  154. var inner = agg.InnerException;
  155. if (inner != null)
  156. {
  157. return GetActualException(inner);
  158. }
  159. else
  160. {
  161. var inners = agg.InnerExceptions;
  162. if (inners.Count > 0)
  163. {
  164. return GetActualException(inners[0]);
  165. }
  166. }
  167. }
  168. return ex;
  169. }
  170. private int GetStatusCode(Exception ex)
  171. {
  172. switch (ex)
  173. {
  174. case ArgumentException _: return 400;
  175. case AuthenticationException _: return 401;
  176. case SecurityException _: return 403;
  177. case DirectoryNotFoundException _:
  178. case FileNotFoundException _:
  179. case ResourceNotFoundException _: return 404;
  180. case MethodNotAllowedException _: return 405;
  181. default: return 500;
  182. }
  183. }
  184. private async Task ErrorHandler(Exception ex, IRequest httpReq, int statusCode, string urlToLog, bool ignoreStackTrace)
  185. {
  186. if (ignoreStackTrace)
  187. {
  188. _logger.LogError("Error processing request: {Message}. URL: {Url}", ex.Message.TrimEnd('.'), urlToLog);
  189. }
  190. else
  191. {
  192. _logger.LogError(ex, "Error processing request. URL: {Url}", urlToLog);
  193. }
  194. var httpRes = httpReq.Response;
  195. if (httpRes.HasStarted)
  196. {
  197. return;
  198. }
  199. httpRes.StatusCode = statusCode;
  200. var errContent = NormalizeExceptionMessage(ex) ?? string.Empty;
  201. httpRes.ContentType = "text/plain";
  202. httpRes.ContentLength = errContent.Length;
  203. await httpRes.WriteAsync(errContent).ConfigureAwait(false);
  204. }
  205. private string NormalizeExceptionMessage(Exception ex)
  206. {
  207. // Do not expose the exception message for AuthenticationException
  208. if (ex is AuthenticationException)
  209. {
  210. return null;
  211. }
  212. // Strip any information we don't want to reveal
  213. return ex.Message
  214. ?.Replace(_config.ApplicationPaths.ProgramSystemPath, string.Empty, StringComparison.OrdinalIgnoreCase)
  215. .Replace(_config.ApplicationPaths.ProgramDataPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  216. }
  217. public static string RemoveQueryStringByKey(string url, string key)
  218. {
  219. var uri = new Uri(url);
  220. // this gets all the query string key value pairs as a collection
  221. var newQueryString = QueryHelpers.ParseQuery(uri.Query);
  222. var originalCount = newQueryString.Count;
  223. if (originalCount == 0)
  224. {
  225. return url;
  226. }
  227. // this removes the key if exists
  228. newQueryString.Remove(key);
  229. if (originalCount == newQueryString.Count)
  230. {
  231. return url;
  232. }
  233. // this gets the page path from root without QueryString
  234. string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
  235. return newQueryString.Count > 0
  236. ? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
  237. : pagePathWithoutQueryString;
  238. }
  239. private static string GetUrlToLog(string url)
  240. {
  241. url = RemoveQueryStringByKey(url, "api_key");
  242. return url;
  243. }
  244. private static string NormalizeConfiguredLocalAddress(string address)
  245. {
  246. var add = address.AsSpan().Trim('/');
  247. int index = add.IndexOf('/');
  248. if (index != -1)
  249. {
  250. add = add.Slice(index + 1);
  251. }
  252. return add.TrimStart('/').ToString();
  253. }
  254. private bool ValidateHost(string host)
  255. {
  256. var hosts = _config
  257. .Configuration
  258. .LocalNetworkAddresses
  259. .Select(NormalizeConfiguredLocalAddress)
  260. .ToList();
  261. if (hosts.Count == 0)
  262. {
  263. return true;
  264. }
  265. host ??= string.Empty;
  266. if (_networkManager.IsInPrivateAddressSpace(host))
  267. {
  268. hosts.Add("localhost");
  269. hosts.Add("127.0.0.1");
  270. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  271. }
  272. return true;
  273. }
  274. private bool ValidateRequest(string remoteIp, bool isLocal)
  275. {
  276. if (isLocal)
  277. {
  278. return true;
  279. }
  280. if (_config.Configuration.EnableRemoteAccess)
  281. {
  282. var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  283. if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
  284. {
  285. if (_config.Configuration.IsRemoteIPFilterBlacklist)
  286. {
  287. return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  288. }
  289. else
  290. {
  291. return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  292. }
  293. }
  294. }
  295. else
  296. {
  297. if (!_networkManager.IsInLocalNetwork(remoteIp))
  298. {
  299. return false;
  300. }
  301. }
  302. return true;
  303. }
  304. /// <summary>
  305. /// Validate a connection from a remote IP address to a URL to see if a redirection to HTTPS is required.
  306. /// </summary>
  307. /// <returns>True if the request is valid, or false if the request is not valid and an HTTPS redirect is required.</returns>
  308. private bool ValidateSsl(string remoteIp, string urlString)
  309. {
  310. if (_config.Configuration.RequireHttps
  311. && _appHost.ListenWithHttps
  312. && !urlString.Contains("https://", StringComparison.OrdinalIgnoreCase))
  313. {
  314. // These are hacks, but if these ever occur on ipv6 in the local network they could be incorrectly redirected
  315. if (urlString.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) != -1
  316. || urlString.IndexOf("dlna/", StringComparison.OrdinalIgnoreCase) != -1)
  317. {
  318. return true;
  319. }
  320. if (!_networkManager.IsInLocalNetwork(remoteIp))
  321. {
  322. return false;
  323. }
  324. }
  325. return true;
  326. }
  327. /// <inheritdoc />
  328. public Task RequestHandler(HttpContext context)
  329. {
  330. if (context.WebSockets.IsWebSocketRequest)
  331. {
  332. return WebSocketRequestHandler(context);
  333. }
  334. var request = context.Request;
  335. var response = context.Response;
  336. var localPath = context.Request.Path.ToString();
  337. var req = new WebSocketSharpRequest(request, response, request.Path, _logger);
  338. return RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted);
  339. }
  340. /// <summary>
  341. /// Overridable method that can be used to implement a custom handler.
  342. /// </summary>
  343. private async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
  344. {
  345. var stopWatch = new Stopwatch();
  346. stopWatch.Start();
  347. var httpRes = httpReq.Response;
  348. string urlToLog = GetUrlToLog(urlString);
  349. string remoteIp = httpReq.RemoteIp;
  350. try
  351. {
  352. if (_disposed)
  353. {
  354. httpRes.StatusCode = 503;
  355. httpRes.ContentType = "text/plain";
  356. await httpRes.WriteAsync("Server shutting down", cancellationToken).ConfigureAwait(false);
  357. return;
  358. }
  359. if (!ValidateHost(host))
  360. {
  361. httpRes.StatusCode = 400;
  362. httpRes.ContentType = "text/plain";
  363. await httpRes.WriteAsync("Invalid host", cancellationToken).ConfigureAwait(false);
  364. return;
  365. }
  366. if (!ValidateRequest(remoteIp, httpReq.IsLocal))
  367. {
  368. httpRes.StatusCode = 403;
  369. httpRes.ContentType = "text/plain";
  370. await httpRes.WriteAsync("Forbidden", cancellationToken).ConfigureAwait(false);
  371. return;
  372. }
  373. if (!ValidateSsl(httpReq.RemoteIp, urlString))
  374. {
  375. RedirectToSecureUrl(httpReq, httpRes, urlString);
  376. return;
  377. }
  378. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  379. {
  380. httpRes.StatusCode = 200;
  381. foreach(var (key, value) in GetDefaultCorsHeaders(httpReq))
  382. {
  383. httpRes.Headers.Add(key, value);
  384. }
  385. httpRes.ContentType = "text/plain";
  386. await httpRes.WriteAsync(string.Empty, cancellationToken).ConfigureAwait(false);
  387. return;
  388. }
  389. if (string.Equals(localPath, _baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase)
  390. || string.Equals(localPath, _baseUrlPrefix, StringComparison.OrdinalIgnoreCase)
  391. || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)
  392. || string.IsNullOrEmpty(localPath)
  393. || !localPath.StartsWith(_baseUrlPrefix, StringComparison.OrdinalIgnoreCase))
  394. {
  395. // Always redirect back to the default path if the base prefix is invalid or missing
  396. _logger.LogDebug("Normalizing a URL at {0}", localPath);
  397. httpRes.Redirect(_baseUrlPrefix + "/" + _defaultRedirectPath);
  398. return;
  399. }
  400. if (!string.IsNullOrEmpty(GlobalResponse))
  401. {
  402. // We don't want the address pings in ApplicationHost to fail
  403. if (localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  404. {
  405. httpRes.StatusCode = 503;
  406. httpRes.ContentType = "text/html";
  407. await httpRes.WriteAsync(GlobalResponse, cancellationToken).ConfigureAwait(false);
  408. return;
  409. }
  410. }
  411. var handler = GetServiceHandler(httpReq);
  412. if (handler != null)
  413. {
  414. await handler.ProcessRequestAsync(this, httpReq, httpRes, _logger, cancellationToken).ConfigureAwait(false);
  415. }
  416. else
  417. {
  418. throw new FileNotFoundException();
  419. }
  420. }
  421. catch (Exception requestEx)
  422. {
  423. try
  424. {
  425. var requestInnerEx = GetActualException(requestEx);
  426. var statusCode = GetStatusCode(requestInnerEx);
  427. foreach (var (key, value) in GetDefaultCorsHeaders(httpReq))
  428. {
  429. if (!httpRes.Headers.ContainsKey(key))
  430. {
  431. httpRes.Headers.Add(key, value);
  432. }
  433. }
  434. bool ignoreStackTrace =
  435. requestInnerEx is SocketException
  436. || requestInnerEx is IOException
  437. || requestInnerEx is OperationCanceledException
  438. || requestInnerEx is SecurityException
  439. || requestInnerEx is AuthenticationException
  440. || requestInnerEx is FileNotFoundException;
  441. // Do not handle 500 server exceptions manually when in development mode.
  442. // Instead, re-throw the exception so it can be handled by the DeveloperExceptionPageMiddleware.
  443. // However, do not use the DeveloperExceptionPageMiddleware when the stack trace should be ignored,
  444. // because it will log the stack trace when it handles the exception.
  445. if (statusCode == 500 && !ignoreStackTrace && _hostEnvironment.IsDevelopment())
  446. {
  447. throw;
  448. }
  449. await ErrorHandler(requestInnerEx, httpReq, statusCode, urlToLog, ignoreStackTrace).ConfigureAwait(false);
  450. }
  451. catch (Exception handlerException)
  452. {
  453. var aggregateEx = new AggregateException("Error while handling request exception", requestEx, handlerException);
  454. _logger.LogError(aggregateEx, "Error while handling exception in response to {Url}", urlToLog);
  455. if (_hostEnvironment.IsDevelopment())
  456. {
  457. throw aggregateEx;
  458. }
  459. }
  460. }
  461. finally
  462. {
  463. if (httpRes.StatusCode >= 500)
  464. {
  465. _logger.LogDebug("Sending HTTP Response 500 in response to {Url}", urlToLog);
  466. }
  467. stopWatch.Stop();
  468. var elapsed = stopWatch.Elapsed;
  469. if (elapsed.TotalMilliseconds > 500)
  470. {
  471. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  472. }
  473. }
  474. }
  475. private async Task WebSocketRequestHandler(HttpContext context)
  476. {
  477. if (_disposed)
  478. {
  479. return;
  480. }
  481. try
  482. {
  483. _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress);
  484. WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
  485. var connection = new WebSocketConnection(
  486. _loggerFactory.CreateLogger<WebSocketConnection>(),
  487. webSocket,
  488. context.Connection.RemoteIpAddress,
  489. context.Request.Query)
  490. {
  491. OnReceive = ProcessWebSocketMessageReceived
  492. };
  493. WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
  494. await connection.ProcessAsync().ConfigureAwait(false);
  495. _logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress);
  496. }
  497. catch (Exception ex) // Otherwise ASP.Net will ignore the exception
  498. {
  499. _logger.LogError(ex, "WS {IP} WebSocketRequestHandler error", context.Connection.RemoteIpAddress);
  500. if (!context.Response.HasStarted)
  501. {
  502. context.Response.StatusCode = 500;
  503. }
  504. }
  505. }
  506. /// <summary>
  507. /// Get the default CORS headers
  508. /// </summary>
  509. /// <param name="req"></param>
  510. /// <returns></returns>
  511. public IDictionary<string, string> GetDefaultCorsHeaders(IRequest req)
  512. {
  513. var origin = req.Headers["Origin"];
  514. if (origin == StringValues.Empty)
  515. {
  516. origin = req.Headers["Host"];
  517. if (origin == StringValues.Empty)
  518. {
  519. origin = "*";
  520. }
  521. }
  522. var headers = new Dictionary<string, string>();
  523. headers.Add("Access-Control-Allow-Origin", origin);
  524. headers.Add("Access-Control-Allow-Credentials", "true");
  525. headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  526. headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization, Cookie");
  527. return headers;
  528. }
  529. // Entry point for HttpListener
  530. public ServiceHandler GetServiceHandler(IHttpRequest httpReq)
  531. {
  532. var pathInfo = httpReq.PathInfo;
  533. pathInfo = ServiceHandler.GetSanitizedPathInfo(pathInfo, out string contentType);
  534. var restPath = ServiceController.GetRestPathForRequest(httpReq.HttpMethod, pathInfo);
  535. if (restPath != null)
  536. {
  537. return new ServiceHandler(restPath, contentType);
  538. }
  539. _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
  540. return null;
  541. }
  542. private void RedirectToSecureUrl(IHttpRequest httpReq, HttpResponse httpRes, string url)
  543. {
  544. if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
  545. {
  546. var builder = new UriBuilder(uri)
  547. {
  548. Port = _config.Configuration.PublicHttpsPort,
  549. Scheme = "https"
  550. };
  551. url = builder.Uri.ToString();
  552. }
  553. httpRes.Redirect(url);
  554. }
  555. /// <summary>
  556. /// Adds the rest handlers.
  557. /// </summary>
  558. /// <param name="serviceTypes">The service types to register with the <see cref="ServiceController"/>.</param>
  559. /// <param name="listeners">The web socket listeners.</param>
  560. /// <param name="urlPrefixes">The URL prefixes. See <see cref="UrlPrefixes"/>.</param>
  561. public void Init(IEnumerable<Type> serviceTypes, IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
  562. {
  563. _webSocketListeners = listeners.ToArray();
  564. UrlPrefixes = urlPrefixes.ToArray();
  565. ServiceController.Init(this, serviceTypes);
  566. ResponseFilters = new Action<IRequest, HttpResponse, object>[]
  567. {
  568. new ResponseFilter(this, _logger).FilterResponse
  569. };
  570. }
  571. public RouteAttribute[] GetRouteAttributes(Type requestType)
  572. {
  573. var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
  574. var clone = routes.ToList();
  575. foreach (var route in clone)
  576. {
  577. routes.Add(new RouteAttribute(NormalizeCustomRoutePath(route.Path), route.Verbs)
  578. {
  579. Notes = route.Notes,
  580. Priority = route.Priority,
  581. Summary = route.Summary
  582. });
  583. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  584. {
  585. Notes = route.Notes,
  586. Priority = route.Priority,
  587. Summary = route.Summary
  588. });
  589. routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
  590. {
  591. Notes = route.Notes,
  592. Priority = route.Priority,
  593. Summary = route.Summary
  594. });
  595. }
  596. return routes.ToArray();
  597. }
  598. public Func<string, object> GetParseFn(Type propertyType)
  599. {
  600. return _funcParseFn(propertyType);
  601. }
  602. public void SerializeToJson(object o, Stream stream)
  603. {
  604. _jsonSerializer.SerializeToStream(o, stream);
  605. }
  606. public void SerializeToXml(object o, Stream stream)
  607. {
  608. _xmlSerializer.SerializeToStream(o, stream);
  609. }
  610. public Task<object> DeserializeXml(Type type, Stream stream)
  611. {
  612. return Task.FromResult(_xmlSerializer.DeserializeFromStream(type, stream));
  613. }
  614. public Task<object> DeserializeJson(Type type, Stream stream)
  615. {
  616. return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
  617. }
  618. private string NormalizeEmbyRoutePath(string path)
  619. {
  620. _logger.LogDebug("Normalizing /emby route");
  621. return _baseUrlPrefix + "/emby" + NormalizeUrlPath(path);
  622. }
  623. private string NormalizeMediaBrowserRoutePath(string path)
  624. {
  625. _logger.LogDebug("Normalizing /mediabrowser route");
  626. return _baseUrlPrefix + "/mediabrowser" + NormalizeUrlPath(path);
  627. }
  628. private string NormalizeCustomRoutePath(string path)
  629. {
  630. _logger.LogDebug("Normalizing custom route {0}", path);
  631. return _baseUrlPrefix + NormalizeUrlPath(path);
  632. }
  633. /// <summary>
  634. /// Processes the web socket message received.
  635. /// </summary>
  636. /// <param name="result">The result.</param>
  637. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  638. {
  639. if (_disposed)
  640. {
  641. return Task.CompletedTask;
  642. }
  643. IEnumerable<Task> GetTasks()
  644. {
  645. foreach (var x in _webSocketListeners)
  646. {
  647. yield return x.ProcessMessageAsync(result);
  648. }
  649. }
  650. return Task.WhenAll(GetTasks());
  651. }
  652. }
  653. }