HttpListenerHost.cs 26 KB

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