HttpListenerHost.cs 25 KB

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