HttpListenerHost.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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. if (!httpRes.Headers.ContainsKey("Access-Control-Allow-Origin"))
  428. {
  429. httpRes.Headers.Add("Access-Control-Allow-Origin", "*");
  430. }
  431. bool ignoreStackTrace =
  432. requestInnerEx is SocketException
  433. || requestInnerEx is IOException
  434. || requestInnerEx is OperationCanceledException
  435. || requestInnerEx is SecurityException
  436. || requestInnerEx is AuthenticationException
  437. || requestInnerEx is FileNotFoundException;
  438. // Do not handle 500 server exceptions manually when in development mode.
  439. // Instead, re-throw the exception so it can be handled by the DeveloperExceptionPageMiddleware.
  440. // However, do not use the DeveloperExceptionPageMiddleware when the stack trace should be ignored,
  441. // because it will log the stack trace when it handles the exception.
  442. if (statusCode == 500 && !ignoreStackTrace && _hostEnvironment.IsDevelopment())
  443. {
  444. throw;
  445. }
  446. await ErrorHandler(requestInnerEx, httpReq, statusCode, urlToLog, ignoreStackTrace).ConfigureAwait(false);
  447. }
  448. catch (Exception handlerException)
  449. {
  450. var aggregateEx = new AggregateException("Error while handling request exception", requestEx, handlerException);
  451. _logger.LogError(aggregateEx, "Error while handling exception in response to {Url}", urlToLog);
  452. if (_hostEnvironment.IsDevelopment())
  453. {
  454. throw aggregateEx;
  455. }
  456. }
  457. }
  458. finally
  459. {
  460. if (httpRes.StatusCode >= 500)
  461. {
  462. _logger.LogDebug("Sending HTTP Response 500 in response to {Url}", urlToLog);
  463. }
  464. stopWatch.Stop();
  465. var elapsed = stopWatch.Elapsed;
  466. if (elapsed.TotalMilliseconds > 500)
  467. {
  468. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  469. }
  470. }
  471. }
  472. private async Task WebSocketRequestHandler(HttpContext context)
  473. {
  474. if (_disposed)
  475. {
  476. return;
  477. }
  478. try
  479. {
  480. _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress);
  481. WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
  482. var connection = new WebSocketConnection(
  483. _loggerFactory.CreateLogger<WebSocketConnection>(),
  484. webSocket,
  485. context.Connection.RemoteIpAddress,
  486. context.Request.Query)
  487. {
  488. OnReceive = ProcessWebSocketMessageReceived
  489. };
  490. WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
  491. await connection.ProcessAsync().ConfigureAwait(false);
  492. _logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress);
  493. }
  494. catch (Exception ex) // Otherwise ASP.Net will ignore the exception
  495. {
  496. _logger.LogError(ex, "WS {IP} WebSocketRequestHandler error", context.Connection.RemoteIpAddress);
  497. if (!context.Response.HasStarted)
  498. {
  499. context.Response.StatusCode = 500;
  500. }
  501. }
  502. }
  503. /// <summary>
  504. /// Get the default CORS headers
  505. /// </summary>
  506. /// <param name="req"></param>
  507. /// <returns></returns>
  508. public IDictionary<string, string> GetDefaultCorsHeaders(IRequest req)
  509. {
  510. var origin = req.Headers["Origin"];
  511. if (origin == StringValues.Empty)
  512. {
  513. origin = req.Headers["Host"];
  514. if (origin == StringValues.Empty)
  515. {
  516. origin = "*";
  517. }
  518. }
  519. var headers = new Dictionary<string, string>();
  520. headers.Add("Access-Control-Allow-Origin", origin);
  521. headers.Add("Access-Control-Allow-Credentials", "true");
  522. headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  523. headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization, Cookie");
  524. return headers;
  525. }
  526. // Entry point for HttpListener
  527. public ServiceHandler GetServiceHandler(IHttpRequest httpReq)
  528. {
  529. var pathInfo = httpReq.PathInfo;
  530. pathInfo = ServiceHandler.GetSanitizedPathInfo(pathInfo, out string contentType);
  531. var restPath = ServiceController.GetRestPathForRequest(httpReq.HttpMethod, pathInfo);
  532. if (restPath != null)
  533. {
  534. return new ServiceHandler(restPath, contentType);
  535. }
  536. _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
  537. return null;
  538. }
  539. private void RedirectToSecureUrl(IHttpRequest httpReq, HttpResponse httpRes, string url)
  540. {
  541. if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
  542. {
  543. var builder = new UriBuilder(uri)
  544. {
  545. Port = _config.Configuration.PublicHttpsPort,
  546. Scheme = "https"
  547. };
  548. url = builder.Uri.ToString();
  549. }
  550. httpRes.Redirect(url);
  551. }
  552. /// <summary>
  553. /// Adds the rest handlers.
  554. /// </summary>
  555. /// <param name="serviceTypes">The service types to register with the <see cref="ServiceController"/>.</param>
  556. /// <param name="listeners">The web socket listeners.</param>
  557. /// <param name="urlPrefixes">The URL prefixes. See <see cref="UrlPrefixes"/>.</param>
  558. public void Init(IEnumerable<Type> serviceTypes, IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
  559. {
  560. _webSocketListeners = listeners.ToArray();
  561. UrlPrefixes = urlPrefixes.ToArray();
  562. ServiceController.Init(this, serviceTypes);
  563. ResponseFilters = new Action<IRequest, HttpResponse, object>[]
  564. {
  565. new ResponseFilter(this, _logger).FilterResponse
  566. };
  567. }
  568. public RouteAttribute[] GetRouteAttributes(Type requestType)
  569. {
  570. var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
  571. var clone = routes.ToList();
  572. foreach (var route in clone)
  573. {
  574. routes.Add(new RouteAttribute(NormalizeCustomRoutePath(route.Path), route.Verbs)
  575. {
  576. Notes = route.Notes,
  577. Priority = route.Priority,
  578. Summary = route.Summary
  579. });
  580. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  581. {
  582. Notes = route.Notes,
  583. Priority = route.Priority,
  584. Summary = route.Summary
  585. });
  586. routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
  587. {
  588. Notes = route.Notes,
  589. Priority = route.Priority,
  590. Summary = route.Summary
  591. });
  592. }
  593. return routes.ToArray();
  594. }
  595. public Func<string, object> GetParseFn(Type propertyType)
  596. {
  597. return _funcParseFn(propertyType);
  598. }
  599. public void SerializeToJson(object o, Stream stream)
  600. {
  601. _jsonSerializer.SerializeToStream(o, stream);
  602. }
  603. public void SerializeToXml(object o, Stream stream)
  604. {
  605. _xmlSerializer.SerializeToStream(o, stream);
  606. }
  607. public Task<object> DeserializeXml(Type type, Stream stream)
  608. {
  609. return Task.FromResult(_xmlSerializer.DeserializeFromStream(type, stream));
  610. }
  611. public Task<object> DeserializeJson(Type type, Stream stream)
  612. {
  613. return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
  614. }
  615. private string NormalizeEmbyRoutePath(string path)
  616. {
  617. _logger.LogDebug("Normalizing /emby route");
  618. return _baseUrlPrefix + "/emby" + NormalizeUrlPath(path);
  619. }
  620. private string NormalizeMediaBrowserRoutePath(string path)
  621. {
  622. _logger.LogDebug("Normalizing /mediabrowser route");
  623. return _baseUrlPrefix + "/mediabrowser" + NormalizeUrlPath(path);
  624. }
  625. private string NormalizeCustomRoutePath(string path)
  626. {
  627. _logger.LogDebug("Normalizing custom route {0}", path);
  628. return _baseUrlPrefix + NormalizeUrlPath(path);
  629. }
  630. /// <summary>
  631. /// Processes the web socket message received.
  632. /// </summary>
  633. /// <param name="result">The result.</param>
  634. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  635. {
  636. if (_disposed)
  637. {
  638. return Task.CompletedTask;
  639. }
  640. IEnumerable<Task> GetTasks()
  641. {
  642. foreach (var x in _webSocketListeners)
  643. {
  644. yield return x.ProcessMessageAsync(result);
  645. }
  646. }
  647. return Task.WhenAll(GetTasks());
  648. }
  649. }
  650. }