HttpListenerHost.cs 25 KB

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