HttpListenerHost.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1600
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net.Sockets;
  9. using System.Net.WebSockets;
  10. using System.Reflection;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using Emby.Server.Implementations.Services;
  14. using Emby.Server.Implementations.SocketSharp;
  15. using MediaBrowser.Common.Extensions;
  16. using MediaBrowser.Common.Net;
  17. using MediaBrowser.Controller;
  18. using MediaBrowser.Controller.Configuration;
  19. using MediaBrowser.Controller.Net;
  20. using MediaBrowser.Model.Events;
  21. using MediaBrowser.Model.Serialization;
  22. using MediaBrowser.Model.Services;
  23. using Microsoft.AspNetCore.Http;
  24. using Microsoft.AspNetCore.Http.Extensions;
  25. using Microsoft.AspNetCore.WebUtilities;
  26. using Microsoft.Extensions.Configuration;
  27. using Microsoft.Extensions.Logging;
  28. using Microsoft.Net.Http.Headers;
  29. using ServiceStack.Text.Jsv;
  30. namespace Emby.Server.Implementations.HttpServer
  31. {
  32. public class HttpListenerHost : IHttpServer, IDisposable
  33. {
  34. private readonly ILogger _logger;
  35. private readonly ILoggerFactory _loggerFactory;
  36. private readonly IServerConfigurationManager _config;
  37. private readonly INetworkManager _networkManager;
  38. private readonly IServerApplicationHost _appHost;
  39. private readonly IJsonSerializer _jsonSerializer;
  40. private readonly IXmlSerializer _xmlSerializer;
  41. private readonly Func<Type, Func<string, object>> _funcParseFn;
  42. private readonly string _defaultRedirectPath;
  43. private readonly string _baseUrlPrefix;
  44. private readonly Dictionary<Type, Type> ServiceOperationsMap = new Dictionary<Type, Type>();
  45. private IWebSocketListener[] _webSocketListeners = Array.Empty<IWebSocketListener>();
  46. private bool _disposed = false;
  47. public HttpListenerHost(
  48. IServerApplicationHost applicationHost,
  49. ILogger<HttpListenerHost> logger,
  50. IServerConfigurationManager config,
  51. IConfiguration configuration,
  52. INetworkManager networkManager,
  53. IJsonSerializer jsonSerializer,
  54. IXmlSerializer xmlSerializer,
  55. ILoggerFactory loggerFactory)
  56. {
  57. _appHost = applicationHost;
  58. _logger = logger;
  59. _config = config;
  60. _defaultRedirectPath = configuration["HttpListenerHost:DefaultRedirectPath"];
  61. _baseUrlPrefix = _config.Configuration.BaseUrl;
  62. _networkManager = networkManager;
  63. _jsonSerializer = jsonSerializer;
  64. _xmlSerializer = xmlSerializer;
  65. _loggerFactory = loggerFactory;
  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 static Exception GetActualException(Exception ex)
  137. {
  138. if (ex is AggregateException agg)
  139. {
  140. var inner = agg.InnerException;
  141. if (inner != null)
  142. {
  143. return GetActualException(inner);
  144. }
  145. else
  146. {
  147. var inners = agg.InnerExceptions;
  148. if (inners != null && inners.Count > 0)
  149. {
  150. return GetActualException(inners[0]);
  151. }
  152. }
  153. }
  154. return ex;
  155. }
  156. private int GetStatusCode(Exception ex)
  157. {
  158. switch (ex)
  159. {
  160. case ArgumentException _: return 400;
  161. case SecurityException _: return 401;
  162. case DirectoryNotFoundException _:
  163. case FileNotFoundException _:
  164. case ResourceNotFoundException _: return 404;
  165. case MethodNotAllowedException _: return 405;
  166. default: return 500;
  167. }
  168. }
  169. private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace)
  170. {
  171. try
  172. {
  173. ex = GetActualException(ex);
  174. if (logExceptionStackTrace)
  175. {
  176. _logger.LogError(ex, "Error processing request");
  177. }
  178. else
  179. {
  180. _logger.LogError("Error processing request: {Message}", ex.Message);
  181. }
  182. var httpRes = httpReq.Response;
  183. if (httpRes.HasStarted)
  184. {
  185. return;
  186. }
  187. var statusCode = GetStatusCode(ex);
  188. httpRes.StatusCode = statusCode;
  189. var errContent = NormalizeExceptionMessage(ex.Message);
  190. httpRes.ContentType = "text/plain";
  191. httpRes.ContentLength = errContent.Length;
  192. await httpRes.WriteAsync(errContent).ConfigureAwait(false);
  193. }
  194. catch (Exception errorEx)
  195. {
  196. _logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)");
  197. }
  198. }
  199. private string NormalizeExceptionMessage(string msg)
  200. {
  201. if (msg == null)
  202. {
  203. return string.Empty;
  204. }
  205. // Strip any information we don't want to reveal
  206. msg = msg.Replace(_config.ApplicationPaths.ProgramSystemPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  207. msg = msg.Replace(_config.ApplicationPaths.ProgramDataPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  208. return msg;
  209. }
  210. public static string RemoveQueryStringByKey(string url, string key)
  211. {
  212. var uri = new Uri(url);
  213. // this gets all the query string key value pairs as a collection
  214. var newQueryString = QueryHelpers.ParseQuery(uri.Query);
  215. var originalCount = newQueryString.Count;
  216. if (originalCount == 0)
  217. {
  218. return url;
  219. }
  220. // this removes the key if exists
  221. newQueryString.Remove(key);
  222. if (originalCount == newQueryString.Count)
  223. {
  224. return url;
  225. }
  226. // this gets the page path from root without QueryString
  227. string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
  228. return newQueryString.Count > 0
  229. ? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
  230. : pagePathWithoutQueryString;
  231. }
  232. private static string GetUrlToLog(string url)
  233. {
  234. url = RemoveQueryStringByKey(url, "api_key");
  235. return url;
  236. }
  237. private static string NormalizeConfiguredLocalAddress(string address)
  238. {
  239. var add = address.AsSpan().Trim('/');
  240. int index = add.IndexOf('/');
  241. if (index != -1)
  242. {
  243. add = add.Slice(index + 1);
  244. }
  245. return add.TrimStart('/').ToString();
  246. }
  247. private bool ValidateHost(string host)
  248. {
  249. var hosts = _config
  250. .Configuration
  251. .LocalNetworkAddresses
  252. .Select(NormalizeConfiguredLocalAddress)
  253. .ToList();
  254. if (hosts.Count == 0)
  255. {
  256. return true;
  257. }
  258. host = host ?? string.Empty;
  259. if (_networkManager.IsInPrivateAddressSpace(host))
  260. {
  261. hosts.Add("localhost");
  262. hosts.Add("127.0.0.1");
  263. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  264. }
  265. return true;
  266. }
  267. private bool ValidateRequest(string remoteIp, bool isLocal)
  268. {
  269. if (isLocal)
  270. {
  271. return true;
  272. }
  273. if (_config.Configuration.EnableRemoteAccess)
  274. {
  275. var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  276. if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
  277. {
  278. if (_config.Configuration.IsRemoteIPFilterBlacklist)
  279. {
  280. return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  281. }
  282. else
  283. {
  284. return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  285. }
  286. }
  287. }
  288. else
  289. {
  290. if (!_networkManager.IsInLocalNetwork(remoteIp))
  291. {
  292. return false;
  293. }
  294. }
  295. return true;
  296. }
  297. private bool ValidateSsl(string remoteIp, string urlString)
  298. {
  299. if (_config.Configuration.RequireHttps
  300. && _appHost.EnableHttps
  301. && !_config.Configuration.IsBehindProxy
  302. && !urlString.Contains("https://", StringComparison.OrdinalIgnoreCase))
  303. {
  304. // These are hacks, but if these ever occur on ipv6 in the local network they could be incorrectly redirected
  305. if (urlString.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) != -1
  306. || urlString.IndexOf("dlna/", StringComparison.OrdinalIgnoreCase) != -1)
  307. {
  308. return true;
  309. }
  310. if (!_networkManager.IsInLocalNetwork(remoteIp))
  311. {
  312. return false;
  313. }
  314. }
  315. return true;
  316. }
  317. /// <inheritdoc />
  318. public Task RequestHandler(HttpContext context)
  319. {
  320. if (context.WebSockets.IsWebSocketRequest)
  321. {
  322. return WebSocketRequestHandler(context);
  323. }
  324. var request = context.Request;
  325. var response = context.Response;
  326. var localPath = context.Request.Path.ToString();
  327. var req = new WebSocketSharpRequest(request, response, request.Path, _logger);
  328. return RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted);
  329. }
  330. /// <summary>
  331. /// Overridable method that can be used to implement a custom handler
  332. /// </summary>
  333. private async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
  334. {
  335. var stopWatch = new Stopwatch();
  336. stopWatch.Start();
  337. var httpRes = httpReq.Response;
  338. string urlToLog = null;
  339. string remoteIp = httpReq.RemoteIp;
  340. try
  341. {
  342. if (_disposed)
  343. {
  344. httpRes.StatusCode = 503;
  345. httpRes.ContentType = "text/plain";
  346. await httpRes.WriteAsync("Server shutting down", cancellationToken).ConfigureAwait(false);
  347. return;
  348. }
  349. if (!ValidateHost(host))
  350. {
  351. httpRes.StatusCode = 400;
  352. httpRes.ContentType = "text/plain";
  353. await httpRes.WriteAsync("Invalid host", cancellationToken).ConfigureAwait(false);
  354. return;
  355. }
  356. if (!ValidateRequest(remoteIp, httpReq.IsLocal))
  357. {
  358. httpRes.StatusCode = 403;
  359. httpRes.ContentType = "text/plain";
  360. await httpRes.WriteAsync("Forbidden", cancellationToken).ConfigureAwait(false);
  361. return;
  362. }
  363. if (!ValidateSsl(httpReq.RemoteIp, urlString))
  364. {
  365. RedirectToSecureUrl(httpReq, httpRes, urlString);
  366. return;
  367. }
  368. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  369. {
  370. httpRes.StatusCode = 200;
  371. httpRes.Headers.Add("Access-Control-Allow-Origin", "*");
  372. httpRes.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  373. httpRes.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
  374. httpRes.ContentType = "text/plain";
  375. await httpRes.WriteAsync(string.Empty, cancellationToken).ConfigureAwait(false);
  376. return;
  377. }
  378. urlToLog = GetUrlToLog(urlString);
  379. if (string.Equals(localPath, _baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase)
  380. || string.Equals(localPath, _baseUrlPrefix, StringComparison.OrdinalIgnoreCase)
  381. || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)
  382. || string.IsNullOrEmpty(localPath)
  383. || !localPath.StartsWith(_baseUrlPrefix))
  384. {
  385. // Always redirect back to the default path if the base prefix is invalid or missing
  386. _logger.LogDebug("Normalizing a URL at {0}", localPath);
  387. httpRes.Redirect(_baseUrlPrefix + "/" + _defaultRedirectPath);
  388. return;
  389. }
  390. if (!string.IsNullOrEmpty(GlobalResponse))
  391. {
  392. // We don't want the address pings in ApplicationHost to fail
  393. if (localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  394. {
  395. httpRes.StatusCode = 503;
  396. httpRes.ContentType = "text/html";
  397. await httpRes.WriteAsync(GlobalResponse, cancellationToken).ConfigureAwait(false);
  398. return;
  399. }
  400. }
  401. var handler = GetServiceHandler(httpReq);
  402. if (handler != null)
  403. {
  404. await handler.ProcessRequestAsync(this, httpReq, httpRes, _logger, cancellationToken).ConfigureAwait(false);
  405. }
  406. else
  407. {
  408. await ErrorHandler(new FileNotFoundException(), httpReq, false).ConfigureAwait(false);
  409. }
  410. }
  411. catch (Exception ex) when (ex is SocketException || ex is IOException || ex is OperationCanceledException)
  412. {
  413. await ErrorHandler(ex, httpReq, false).ConfigureAwait(false);
  414. }
  415. catch (SecurityException ex)
  416. {
  417. await ErrorHandler(ex, httpReq, false).ConfigureAwait(false);
  418. }
  419. catch (Exception ex)
  420. {
  421. var logException = !string.Equals(ex.GetType().Name, "SocketException", StringComparison.OrdinalIgnoreCase);
  422. await ErrorHandler(ex, httpReq, logException).ConfigureAwait(false);
  423. }
  424. finally
  425. {
  426. if (httpRes.StatusCode >= 500)
  427. {
  428. _logger.LogDebug("Sending HTTP Response 500 in response to {Url}", urlToLog);
  429. }
  430. stopWatch.Stop();
  431. var elapsed = stopWatch.Elapsed;
  432. if (elapsed.TotalMilliseconds > 500)
  433. {
  434. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  435. }
  436. }
  437. }
  438. private async Task WebSocketRequestHandler(HttpContext context)
  439. {
  440. if (_disposed)
  441. {
  442. return;
  443. }
  444. try
  445. {
  446. _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress);
  447. WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
  448. var connection = new WebSocketConnection(
  449. _loggerFactory.CreateLogger<WebSocketConnection>(),
  450. webSocket,
  451. context.Connection.RemoteIpAddress,
  452. context.Request.Query)
  453. {
  454. OnReceive = ProcessWebSocketMessageReceived
  455. };
  456. WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
  457. await connection.ProcessAsync().ConfigureAwait(false);
  458. _logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress);
  459. }
  460. catch (Exception ex) // Otherwise ASP.Net will ignore the exception
  461. {
  462. _logger.LogError(ex, "WS {IP} WebSocketRequestHandler error", context.Connection.RemoteIpAddress);
  463. if (!context.Response.HasStarted)
  464. {
  465. context.Response.StatusCode = 500;
  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. private string NormalizeEmbyRoutePath(string path)
  561. {
  562. _logger.LogDebug("Normalizing /emby route");
  563. return _baseUrlPrefix + "/emby" + NormalizeUrlPath(path);
  564. }
  565. private string NormalizeMediaBrowserRoutePath(string path)
  566. {
  567. _logger.LogDebug("Normalizing /mediabrowser route");
  568. return _baseUrlPrefix + "/mediabrowser" + NormalizeUrlPath(path);
  569. }
  570. private string NormalizeCustomRoutePath(string path)
  571. {
  572. _logger.LogDebug("Normalizing custom route {0}", path);
  573. return _baseUrlPrefix + NormalizeUrlPath(path);
  574. }
  575. /// <inheritdoc />
  576. public void Dispose()
  577. {
  578. Dispose(true);
  579. GC.SuppressFinalize(this);
  580. }
  581. protected virtual void Dispose(bool disposing)
  582. {
  583. if (_disposed) return;
  584. if (disposing)
  585. {
  586. // TODO:
  587. }
  588. _disposed = true;
  589. }
  590. /// <summary>
  591. /// Processes the web socket message received.
  592. /// </summary>
  593. /// <param name="result">The result.</param>
  594. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  595. {
  596. if (_disposed)
  597. {
  598. return Task.CompletedTask;
  599. }
  600. IEnumerable<Task> GetTasks()
  601. {
  602. foreach (var x in _webSocketListeners)
  603. {
  604. yield return x.ProcessMessageAsync(result);
  605. }
  606. }
  607. return Task.WhenAll(GetTasks());
  608. }
  609. }
  610. }