HttpListenerHost.cs 25 KB

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