HttpListenerHost.cs 26 KB

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