HttpListenerHost.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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, bool logExceptionMessage)
  197. {
  198. try
  199. {
  200. ex = GetActualException(ex);
  201. if (logExceptionStackTrace)
  202. {
  203. _logger.LogError(ex, "Error processing request");
  204. }
  205. else if (logExceptionMessage)
  206. {
  207. _logger.LogError(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. httpRes.ContentType = "text/html";
  217. await httpRes.WriteAsync(NormalizeExceptionMessage(ex.Message)).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, 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, false).ConfigureAwait(false);
  449. }
  450. catch (SecurityException ex)
  451. {
  452. await ErrorHandler(ex, httpReq, false, true).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, false).ConfigureAwait(false);
  458. }
  459. finally
  460. {
  461. stopWatch.Stop();
  462. var elapsed = stopWatch.Elapsed;
  463. if (elapsed.TotalMilliseconds > 500)
  464. {
  465. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  466. }
  467. }
  468. }
  469. // Entry point for HttpListener
  470. public ServiceHandler GetServiceHandler(IHttpRequest httpReq)
  471. {
  472. var pathInfo = httpReq.PathInfo;
  473. pathInfo = ServiceHandler.GetSanitizedPathInfo(pathInfo, out string contentType);
  474. var restPath = ServiceController.GetRestPathForRequest(httpReq.HttpMethod, pathInfo);
  475. if (restPath != null)
  476. {
  477. return new ServiceHandler(restPath, contentType);
  478. }
  479. _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
  480. return null;
  481. }
  482. private void RedirectToSecureUrl(IHttpRequest httpReq, HttpResponse httpRes, string url)
  483. {
  484. if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
  485. {
  486. var builder = new UriBuilder(uri)
  487. {
  488. Port = _config.Configuration.PublicHttpsPort,
  489. Scheme = "https"
  490. };
  491. url = builder.Uri.ToString();
  492. }
  493. httpRes.Redirect(url);
  494. }
  495. /// <summary>
  496. /// Adds the rest handlers.
  497. /// </summary>
  498. /// <param name="services">The services.</param>
  499. /// <param name="listeners"></param>
  500. /// <param name="urlPrefixes"></param>
  501. public void Init(IEnumerable<IService> services, IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
  502. {
  503. _webSocketListeners = listeners.ToArray();
  504. UrlPrefixes = urlPrefixes.ToArray();
  505. ServiceController = new ServiceController();
  506. var types = services.Select(r => r.GetType());
  507. ServiceController.Init(this, types);
  508. ResponseFilters = new Action<IRequest, HttpResponse, object>[]
  509. {
  510. new ResponseFilter(_logger).FilterResponse
  511. };
  512. }
  513. public RouteAttribute[] GetRouteAttributes(Type requestType)
  514. {
  515. var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
  516. var clone = routes.ToList();
  517. foreach (var route in clone)
  518. {
  519. routes.Add(new RouteAttribute(NormalizeCustomRoutePath(route.Path), route.Verbs)
  520. {
  521. Notes = route.Notes,
  522. Priority = route.Priority,
  523. Summary = route.Summary
  524. });
  525. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  526. {
  527. Notes = route.Notes,
  528. Priority = route.Priority,
  529. Summary = route.Summary
  530. });
  531. routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
  532. {
  533. Notes = route.Notes,
  534. Priority = route.Priority,
  535. Summary = route.Summary
  536. });
  537. }
  538. return routes.ToArray();
  539. }
  540. public Func<string, object> GetParseFn(Type propertyType)
  541. {
  542. return _funcParseFn(propertyType);
  543. }
  544. public void SerializeToJson(object o, Stream stream)
  545. {
  546. _jsonSerializer.SerializeToStream(o, stream);
  547. }
  548. public void SerializeToXml(object o, Stream stream)
  549. {
  550. _xmlSerializer.SerializeToStream(o, stream);
  551. }
  552. public Task<object> DeserializeXml(Type type, Stream stream)
  553. {
  554. return Task.FromResult(_xmlSerializer.DeserializeFromStream(type, stream));
  555. }
  556. public Task<object> DeserializeJson(Type type, Stream stream)
  557. {
  558. return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
  559. }
  560. public Task ProcessWebSocketRequest(HttpContext context)
  561. {
  562. return _socketListener.ProcessWebSocketRequest(context);
  563. }
  564. private string NormalizeEmbyRoutePath(string path)
  565. {
  566. _logger.LogDebug("Normalizing /emby route");
  567. return _baseUrlPrefix + "/emby" + NormalizeUrlPath(path);
  568. }
  569. private string NormalizeMediaBrowserRoutePath(string path)
  570. {
  571. _logger.LogDebug("Normalizing /mediabrowser route");
  572. return _baseUrlPrefix + "/mediabrowser" + NormalizeUrlPath(path);
  573. }
  574. private string NormalizeCustomRoutePath(string path)
  575. {
  576. _logger.LogDebug("Normalizing custom route {0}", path);
  577. return _baseUrlPrefix + NormalizeUrlPath(path);
  578. }
  579. /// <inheritdoc />
  580. public void Dispose()
  581. {
  582. Dispose(true);
  583. GC.SuppressFinalize(this);
  584. }
  585. protected virtual void Dispose(bool disposing)
  586. {
  587. if (_disposed) return;
  588. if (disposing)
  589. {
  590. Stop();
  591. }
  592. _disposed = true;
  593. }
  594. /// <summary>
  595. /// Processes the web socket message received.
  596. /// </summary>
  597. /// <param name="result">The result.</param>
  598. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  599. {
  600. if (_disposed)
  601. {
  602. return Task.CompletedTask;
  603. }
  604. _logger.LogDebug("Websocket message received: {0}", result.MessageType);
  605. IEnumerable<Task> GetTasks()
  606. {
  607. foreach (var x in _webSocketListeners)
  608. {
  609. yield return x.ProcessMessageAsync(result);
  610. }
  611. }
  612. return Task.WhenAll(GetTasks());
  613. }
  614. }
  615. }