HttpListenerHost.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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. 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 readonly List<IWebSocketConnection> _webSocketConnections = new List<IWebSocketConnection>();
  43. private IWebSocketListener[] _webSocketListeners = Array.Empty<IWebSocketListener>();
  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 event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
  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 object CreateInstance(Type type)
  76. {
  77. return _appHost.CreateInstance(type);
  78. }
  79. private static string NormalizeUrlPath(string path)
  80. {
  81. if (path.Length > 0 && path[0] == '/')
  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
  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.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. default: return 500;
  192. }
  193. }
  194. private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace, string urlToLog)
  195. {
  196. try
  197. {
  198. ex = GetActualException(ex);
  199. if (logExceptionStackTrace)
  200. {
  201. _logger.LogError(ex, "Error processing request. URL: {Url}", urlToLog);
  202. }
  203. else
  204. {
  205. _logger.LogError("Error processing request: {Message}. URL: {Url}", ex.Message.TrimEnd('.'), urlToLog);
  206. }
  207. var httpRes = httpReq.Response;
  208. if (httpRes.HasStarted)
  209. {
  210. return;
  211. }
  212. var statusCode = GetStatusCode(ex);
  213. httpRes.StatusCode = statusCode;
  214. var errContent = NormalizeExceptionMessage(ex.Message);
  215. httpRes.ContentType = "text/plain";
  216. httpRes.ContentLength = errContent.Length;
  217. await httpRes.WriteAsync(errContent).ConfigureAwait(false);
  218. }
  219. catch (Exception errorEx)
  220. {
  221. _logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response). URL: {Url}", urlToLog);
  222. }
  223. }
  224. private string NormalizeExceptionMessage(string msg)
  225. {
  226. if (msg == null)
  227. {
  228. return string.Empty;
  229. }
  230. // Strip any information we don't want to reveal
  231. msg = msg.Replace(_config.ApplicationPaths.ProgramSystemPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  232. msg = msg.Replace(_config.ApplicationPaths.ProgramDataPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  233. return msg;
  234. }
  235. /// <summary>
  236. /// Shut down the Web Service
  237. /// </summary>
  238. public void Stop()
  239. {
  240. List<IWebSocketConnection> connections;
  241. lock (_webSocketConnections)
  242. {
  243. connections = _webSocketConnections.ToList();
  244. _webSocketConnections.Clear();
  245. }
  246. foreach (var connection in connections)
  247. {
  248. try
  249. {
  250. connection.Dispose();
  251. }
  252. catch (Exception ex)
  253. {
  254. _logger.LogError(ex, "Error disposing connection");
  255. }
  256. }
  257. }
  258. public static string RemoveQueryStringByKey(string url, string key)
  259. {
  260. var uri = new Uri(url);
  261. // this gets all the query string key value pairs as a collection
  262. var newQueryString = QueryHelpers.ParseQuery(uri.Query);
  263. var originalCount = newQueryString.Count;
  264. if (originalCount == 0)
  265. {
  266. return url;
  267. }
  268. // this removes the key if exists
  269. newQueryString.Remove(key);
  270. if (originalCount == newQueryString.Count)
  271. {
  272. return url;
  273. }
  274. // this gets the page path from root without QueryString
  275. string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
  276. return newQueryString.Count > 0
  277. ? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
  278. : pagePathWithoutQueryString;
  279. }
  280. private static string GetUrlToLog(string url)
  281. {
  282. url = RemoveQueryStringByKey(url, "api_key");
  283. return url;
  284. }
  285. private static string NormalizeConfiguredLocalAddress(string address)
  286. {
  287. var add = address.AsSpan().Trim('/');
  288. int index = add.IndexOf('/');
  289. if (index != -1)
  290. {
  291. add = add.Slice(index + 1);
  292. }
  293. return add.TrimStart('/').ToString();
  294. }
  295. private bool ValidateHost(string host)
  296. {
  297. var hosts = _config
  298. .Configuration
  299. .LocalNetworkAddresses
  300. .Select(NormalizeConfiguredLocalAddress)
  301. .ToList();
  302. if (hosts.Count == 0)
  303. {
  304. return true;
  305. }
  306. host ??= string.Empty;
  307. if (_networkManager.IsInPrivateAddressSpace(host))
  308. {
  309. hosts.Add("localhost");
  310. hosts.Add("127.0.0.1");
  311. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  312. }
  313. return true;
  314. }
  315. private bool ValidateRequest(string remoteIp, bool isLocal)
  316. {
  317. if (isLocal)
  318. {
  319. return true;
  320. }
  321. if (_config.Configuration.EnableRemoteAccess)
  322. {
  323. var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  324. if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
  325. {
  326. if (_config.Configuration.IsRemoteIPFilterBlacklist)
  327. {
  328. return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  329. }
  330. else
  331. {
  332. return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  333. }
  334. }
  335. }
  336. else
  337. {
  338. if (!_networkManager.IsInLocalNetwork(remoteIp))
  339. {
  340. return false;
  341. }
  342. }
  343. return true;
  344. }
  345. private bool ValidateSsl(string remoteIp, string urlString)
  346. {
  347. if (_config.Configuration.RequireHttps && _appHost.EnableHttps && !_config.Configuration.IsBehindProxy)
  348. {
  349. if (urlString.IndexOf("https://", StringComparison.OrdinalIgnoreCase) == -1)
  350. {
  351. // These are hacks, but if these ever occur on ipv6 in the local network they could be incorrectly redirected
  352. if (urlString.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) != -1
  353. || urlString.IndexOf("dlna/", StringComparison.OrdinalIgnoreCase) != -1)
  354. {
  355. return true;
  356. }
  357. if (!_networkManager.IsInLocalNetwork(remoteIp))
  358. {
  359. return false;
  360. }
  361. }
  362. }
  363. return true;
  364. }
  365. /// <summary>
  366. /// Overridable method that can be used to implement a custom handler.
  367. /// </summary>
  368. public async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
  369. {
  370. var stopWatch = new Stopwatch();
  371. stopWatch.Start();
  372. var httpRes = httpReq.Response;
  373. string urlToLog = GetUrlToLog(urlString);
  374. string remoteIp = httpReq.RemoteIp;
  375. try
  376. {
  377. if (_disposed)
  378. {
  379. httpRes.StatusCode = 503;
  380. httpRes.ContentType = "text/plain";
  381. await httpRes.WriteAsync("Server shutting down", cancellationToken).ConfigureAwait(false);
  382. return;
  383. }
  384. if (!ValidateHost(host))
  385. {
  386. httpRes.StatusCode = 400;
  387. httpRes.ContentType = "text/plain";
  388. await httpRes.WriteAsync("Invalid host", cancellationToken).ConfigureAwait(false);
  389. return;
  390. }
  391. if (!ValidateRequest(remoteIp, httpReq.IsLocal))
  392. {
  393. httpRes.StatusCode = 403;
  394. httpRes.ContentType = "text/plain";
  395. await httpRes.WriteAsync("Forbidden", cancellationToken).ConfigureAwait(false);
  396. return;
  397. }
  398. if (!ValidateSsl(httpReq.RemoteIp, urlString))
  399. {
  400. RedirectToSecureUrl(httpReq, httpRes, urlString);
  401. return;
  402. }
  403. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  404. {
  405. httpRes.StatusCode = 200;
  406. httpRes.Headers.Add("Access-Control-Allow-Origin", "*");
  407. httpRes.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  408. httpRes.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
  409. httpRes.ContentType = "text/plain";
  410. await httpRes.WriteAsync(string.Empty, cancellationToken).ConfigureAwait(false);
  411. return;
  412. }
  413. 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, StringComparison.OrdinalIgnoreCase))
  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, urlToLog).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, urlToLog).ConfigureAwait(false);
  448. }
  449. catch (SecurityException ex)
  450. {
  451. await ErrorHandler(ex, httpReq, false, urlToLog).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, urlToLog).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)
  591. {
  592. return;
  593. }
  594. if (disposing)
  595. {
  596. Stop();
  597. }
  598. _disposed = true;
  599. }
  600. /// <summary>
  601. /// Processes the web socket message received.
  602. /// </summary>
  603. /// <param name="result">The result.</param>
  604. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  605. {
  606. if (_disposed)
  607. {
  608. return Task.CompletedTask;
  609. }
  610. _logger.LogDebug("Websocket message received: {0}", result.MessageType);
  611. IEnumerable<Task> GetTasks()
  612. {
  613. foreach (var x in _webSocketListeners)
  614. {
  615. yield return x.ProcessMessageAsync(result);
  616. }
  617. }
  618. return Task.WhenAll(GetTasks());
  619. }
  620. }
  621. }