HttpListenerHost.cs 26 KB

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