HttpListenerHost.cs 26 KB

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