HttpListenerHost.cs 26 KB

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