HttpListenerHost.cs 26 KB

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