HttpListenerHost.cs 25 KB

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