HttpListenerHost.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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. ServiceController serviceController)
  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. ServiceController = serviceController;
  72. _socketListener.WebSocketConnected = OnWebSocketConnected;
  73. _funcParseFn = t => s => JsvReader.GetParseFn(t)(s);
  74. Instance = this;
  75. ResponseFilters = Array.Empty<Action<IRequest, HttpResponse, object>>();
  76. GlobalResponse = localizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
  77. }
  78. public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
  79. public Action<IRequest, HttpResponse, object>[] ResponseFilters { get; set; }
  80. public static HttpListenerHost Instance { get; protected set; }
  81. public string[] UrlPrefixes { get; private set; }
  82. public string GlobalResponse { get; set; }
  83. public ServiceController ServiceController { get; }
  84. public object CreateInstance(Type type)
  85. {
  86. return _appHost.CreateInstance(type);
  87. }
  88. private static string NormalizeUrlPath(string path)
  89. {
  90. if (path.Length > 0 && path[0] == '/')
  91. {
  92. // If the path begins with a leading slash, just return it as-is
  93. return path;
  94. }
  95. else
  96. {
  97. // If the path does not begin with a leading slash, append one for consistency
  98. return "/" + path;
  99. }
  100. }
  101. /// <summary>
  102. /// Applies the request filters. Returns whether or not the request has been handled
  103. /// and no more processing should be done.
  104. /// </summary>
  105. /// <returns></returns>
  106. public void ApplyRequestFilters(IRequest req, HttpResponse res, object requestDto)
  107. {
  108. // Exec all RequestFilter attributes with Priority < 0
  109. var attributes = GetRequestFilterAttributes(requestDto.GetType());
  110. int count = attributes.Count;
  111. int i = 0;
  112. for (; i < count && attributes[i].Priority < 0; i++)
  113. {
  114. var attribute = attributes[i];
  115. attribute.RequestFilter(req, res, requestDto);
  116. }
  117. // Exec remaining RequestFilter attributes with Priority >= 0
  118. for (; i < count && attributes[i].Priority >= 0; i++)
  119. {
  120. var attribute = attributes[i];
  121. attribute.RequestFilter(req, res, requestDto);
  122. }
  123. }
  124. public Type GetServiceTypeByRequest(Type requestType)
  125. {
  126. _serviceOperationsMap.TryGetValue(requestType, out var serviceType);
  127. return serviceType;
  128. }
  129. public void AddServiceInfo(Type serviceType, Type requestType)
  130. {
  131. _serviceOperationsMap[requestType] = serviceType;
  132. }
  133. private List<IHasRequestFilter> GetRequestFilterAttributes(Type requestDtoType)
  134. {
  135. var attributes = requestDtoType.GetCustomAttributes(true).OfType<IHasRequestFilter>().ToList();
  136. var serviceType = GetServiceTypeByRequest(requestDtoType);
  137. if (serviceType != null)
  138. {
  139. attributes.AddRange(serviceType.GetCustomAttributes(true).OfType<IHasRequestFilter>());
  140. }
  141. attributes.Sort((x, y) => x.Priority - y.Priority);
  142. return attributes;
  143. }
  144. private void OnWebSocketConnected(WebSocketConnectEventArgs e)
  145. {
  146. if (_disposed)
  147. {
  148. return;
  149. }
  150. var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger)
  151. {
  152. OnReceive = ProcessWebSocketMessageReceived,
  153. Url = e.Url,
  154. QueryString = e.QueryString
  155. };
  156. connection.Closed += OnConnectionClosed;
  157. lock (_webSocketConnections)
  158. {
  159. _webSocketConnections.Add(connection);
  160. }
  161. WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
  162. }
  163. private void OnConnectionClosed(object sender, EventArgs e)
  164. {
  165. lock (_webSocketConnections)
  166. {
  167. _webSocketConnections.Remove((IWebSocketConnection)sender);
  168. }
  169. }
  170. private static Exception GetActualException(Exception ex)
  171. {
  172. if (ex is AggregateException agg)
  173. {
  174. var inner = agg.InnerException;
  175. if (inner != null)
  176. {
  177. return GetActualException(inner);
  178. }
  179. else
  180. {
  181. var inners = agg.InnerExceptions;
  182. if (inners.Count > 0)
  183. {
  184. return GetActualException(inners[0]);
  185. }
  186. }
  187. }
  188. return ex;
  189. }
  190. private int GetStatusCode(Exception ex)
  191. {
  192. switch (ex)
  193. {
  194. case ArgumentException _: return 400;
  195. case SecurityException _: return 401;
  196. case DirectoryNotFoundException _:
  197. case FileNotFoundException _:
  198. case ResourceNotFoundException _: return 404;
  199. case MethodNotAllowedException _: return 405;
  200. default: return 500;
  201. }
  202. }
  203. private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace)
  204. {
  205. try
  206. {
  207. ex = GetActualException(ex);
  208. if (logExceptionStackTrace)
  209. {
  210. _logger.LogError(ex, "Error processing request");
  211. }
  212. else
  213. {
  214. _logger.LogError("Error processing request: {Message}", ex.Message);
  215. }
  216. var httpRes = httpReq.Response;
  217. if (httpRes.HasStarted)
  218. {
  219. return;
  220. }
  221. var statusCode = GetStatusCode(ex);
  222. httpRes.StatusCode = statusCode;
  223. var errContent = NormalizeExceptionMessage(ex.Message);
  224. httpRes.ContentType = "text/plain";
  225. httpRes.ContentLength = errContent.Length;
  226. await httpRes.WriteAsync(errContent).ConfigureAwait(false);
  227. }
  228. catch (Exception errorEx)
  229. {
  230. _logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)");
  231. }
  232. }
  233. private string NormalizeExceptionMessage(string msg)
  234. {
  235. if (msg == null)
  236. {
  237. return string.Empty;
  238. }
  239. // Strip any information we don't want to reveal
  240. msg = msg.Replace(_config.ApplicationPaths.ProgramSystemPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  241. msg = msg.Replace(_config.ApplicationPaths.ProgramDataPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  242. return msg;
  243. }
  244. /// <summary>
  245. /// Shut down the Web Service
  246. /// </summary>
  247. public void Stop()
  248. {
  249. List<IWebSocketConnection> connections;
  250. lock (_webSocketConnections)
  251. {
  252. connections = _webSocketConnections.ToList();
  253. _webSocketConnections.Clear();
  254. }
  255. foreach (var connection in connections)
  256. {
  257. try
  258. {
  259. connection.Dispose();
  260. }
  261. catch (Exception ex)
  262. {
  263. _logger.LogError(ex, "Error disposing connection");
  264. }
  265. }
  266. }
  267. public static string RemoveQueryStringByKey(string url, string key)
  268. {
  269. var uri = new Uri(url);
  270. // this gets all the query string key value pairs as a collection
  271. var newQueryString = QueryHelpers.ParseQuery(uri.Query);
  272. var originalCount = newQueryString.Count;
  273. if (originalCount == 0)
  274. {
  275. return url;
  276. }
  277. // this removes the key if exists
  278. newQueryString.Remove(key);
  279. if (originalCount == newQueryString.Count)
  280. {
  281. return url;
  282. }
  283. // this gets the page path from root without QueryString
  284. string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
  285. return newQueryString.Count > 0
  286. ? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
  287. : pagePathWithoutQueryString;
  288. }
  289. private static string GetUrlToLog(string url)
  290. {
  291. url = RemoveQueryStringByKey(url, "api_key");
  292. return url;
  293. }
  294. private static string NormalizeConfiguredLocalAddress(string address)
  295. {
  296. var add = address.AsSpan().Trim('/');
  297. int index = add.IndexOf('/');
  298. if (index != -1)
  299. {
  300. add = add.Slice(index + 1);
  301. }
  302. return add.TrimStart('/').ToString();
  303. }
  304. private bool ValidateHost(string host)
  305. {
  306. var hosts = _config
  307. .Configuration
  308. .LocalNetworkAddresses
  309. .Select(NormalizeConfiguredLocalAddress)
  310. .ToList();
  311. if (hosts.Count == 0)
  312. {
  313. return true;
  314. }
  315. host ??= string.Empty;
  316. if (_networkManager.IsInPrivateAddressSpace(host))
  317. {
  318. hosts.Add("localhost");
  319. hosts.Add("127.0.0.1");
  320. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  321. }
  322. return true;
  323. }
  324. private bool ValidateRequest(string remoteIp, bool isLocal)
  325. {
  326. if (isLocal)
  327. {
  328. return true;
  329. }
  330. if (_config.Configuration.EnableRemoteAccess)
  331. {
  332. var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  333. if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
  334. {
  335. if (_config.Configuration.IsRemoteIPFilterBlacklist)
  336. {
  337. return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  338. }
  339. else
  340. {
  341. return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  342. }
  343. }
  344. }
  345. else
  346. {
  347. if (!_networkManager.IsInLocalNetwork(remoteIp))
  348. {
  349. return false;
  350. }
  351. }
  352. return true;
  353. }
  354. private bool ValidateSsl(string remoteIp, string urlString)
  355. {
  356. if (_config.Configuration.RequireHttps && _appHost.EnableHttps && !_config.Configuration.IsBehindProxy)
  357. {
  358. if (urlString.IndexOf("https://", StringComparison.OrdinalIgnoreCase) == -1)
  359. {
  360. // These are hacks, but if these ever occur on ipv6 in the local network they could be incorrectly redirected
  361. if (urlString.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) != -1
  362. || urlString.IndexOf("dlna/", StringComparison.OrdinalIgnoreCase) != -1)
  363. {
  364. return true;
  365. }
  366. if (!_networkManager.IsInLocalNetwork(remoteIp))
  367. {
  368. return false;
  369. }
  370. }
  371. }
  372. return true;
  373. }
  374. /// <summary>
  375. /// Overridable method that can be used to implement a custom handler.
  376. /// </summary>
  377. public async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
  378. {
  379. var stopWatch = new Stopwatch();
  380. stopWatch.Start();
  381. var httpRes = httpReq.Response;
  382. string urlToLog = null;
  383. string remoteIp = httpReq.RemoteIp;
  384. try
  385. {
  386. if (_disposed)
  387. {
  388. httpRes.StatusCode = 503;
  389. httpRes.ContentType = "text/plain";
  390. await httpRes.WriteAsync("Server shutting down", cancellationToken).ConfigureAwait(false);
  391. return;
  392. }
  393. if (!ValidateHost(host))
  394. {
  395. httpRes.StatusCode = 400;
  396. httpRes.ContentType = "text/plain";
  397. await httpRes.WriteAsync("Invalid host", cancellationToken).ConfigureAwait(false);
  398. return;
  399. }
  400. if (!ValidateRequest(remoteIp, httpReq.IsLocal))
  401. {
  402. httpRes.StatusCode = 403;
  403. httpRes.ContentType = "text/plain";
  404. await httpRes.WriteAsync("Forbidden", cancellationToken).ConfigureAwait(false);
  405. return;
  406. }
  407. if (!ValidateSsl(httpReq.RemoteIp, urlString))
  408. {
  409. RedirectToSecureUrl(httpReq, httpRes, urlString);
  410. return;
  411. }
  412. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  413. {
  414. httpRes.StatusCode = 200;
  415. httpRes.Headers.Add("Access-Control-Allow-Origin", "*");
  416. httpRes.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  417. httpRes.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
  418. httpRes.ContentType = "text/plain";
  419. await httpRes.WriteAsync(string.Empty, cancellationToken).ConfigureAwait(false);
  420. return;
  421. }
  422. urlToLog = GetUrlToLog(urlString);
  423. if (string.Equals(localPath, _baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase)
  424. || string.Equals(localPath, _baseUrlPrefix, StringComparison.OrdinalIgnoreCase)
  425. || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)
  426. || string.IsNullOrEmpty(localPath)
  427. || !localPath.StartsWith(_baseUrlPrefix, StringComparison.OrdinalIgnoreCase))
  428. {
  429. // Always redirect back to the default path if the base prefix is invalid or missing
  430. _logger.LogDebug("Normalizing a URL at {0}", localPath);
  431. httpRes.Redirect(_baseUrlPrefix + "/" + _defaultRedirectPath);
  432. return;
  433. }
  434. if (!string.IsNullOrEmpty(GlobalResponse))
  435. {
  436. // We don't want the address pings in ApplicationHost to fail
  437. if (localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  438. {
  439. httpRes.StatusCode = 503;
  440. httpRes.ContentType = "text/html";
  441. await httpRes.WriteAsync(GlobalResponse, cancellationToken).ConfigureAwait(false);
  442. return;
  443. }
  444. }
  445. var handler = GetServiceHandler(httpReq);
  446. if (handler != null)
  447. {
  448. await handler.ProcessRequestAsync(this, httpReq, httpRes, _logger, cancellationToken).ConfigureAwait(false);
  449. }
  450. else
  451. {
  452. await ErrorHandler(new FileNotFoundException(), httpReq, false).ConfigureAwait(false);
  453. }
  454. }
  455. catch (Exception ex) when (ex is SocketException || ex is IOException || ex is OperationCanceledException)
  456. {
  457. await ErrorHandler(ex, httpReq, false).ConfigureAwait(false);
  458. }
  459. catch (SecurityException ex)
  460. {
  461. await ErrorHandler(ex, httpReq, false).ConfigureAwait(false);
  462. }
  463. catch (Exception ex)
  464. {
  465. var logException = !string.Equals(ex.GetType().Name, "SocketException", StringComparison.OrdinalIgnoreCase);
  466. await ErrorHandler(ex, httpReq, logException).ConfigureAwait(false);
  467. }
  468. finally
  469. {
  470. if (httpRes.StatusCode >= 500)
  471. {
  472. _logger.LogDebug("Sending HTTP Response 500 in response to {Url}", urlToLog);
  473. }
  474. stopWatch.Stop();
  475. var elapsed = stopWatch.Elapsed;
  476. if (elapsed.TotalMilliseconds > 500)
  477. {
  478. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  479. }
  480. }
  481. }
  482. // Entry point for HttpListener
  483. public ServiceHandler GetServiceHandler(IHttpRequest httpReq)
  484. {
  485. var pathInfo = httpReq.PathInfo;
  486. pathInfo = ServiceHandler.GetSanitizedPathInfo(pathInfo, out string contentType);
  487. var restPath = ServiceController.GetRestPathForRequest(httpReq.HttpMethod, pathInfo);
  488. if (restPath != null)
  489. {
  490. return new ServiceHandler(restPath, contentType);
  491. }
  492. _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
  493. return null;
  494. }
  495. private void RedirectToSecureUrl(IHttpRequest httpReq, HttpResponse httpRes, string url)
  496. {
  497. if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
  498. {
  499. var builder = new UriBuilder(uri)
  500. {
  501. Port = _config.Configuration.PublicHttpsPort,
  502. Scheme = "https"
  503. };
  504. url = builder.Uri.ToString();
  505. }
  506. httpRes.Redirect(url);
  507. }
  508. /// <summary>
  509. /// Adds the rest handlers.
  510. /// </summary>
  511. /// <param name="serviceTypes">The service types to register with the <see cref="ServiceController"/>.</param>
  512. /// <param name="listeners">The web socket listeners.</param>
  513. /// <param name="urlPrefixes">The URL prefixes. See <see cref="UrlPrefixes"/>.</param>
  514. public void Init(IEnumerable<Type> serviceTypes, IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
  515. {
  516. _webSocketListeners = listeners.ToArray();
  517. UrlPrefixes = urlPrefixes.ToArray();
  518. ServiceController.Init(this, serviceTypes);
  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. }