HttpListenerHost.cs 25 KB

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