HttpListenerHost.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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, int statusCode, string urlToLog)
  210. {
  211. bool ignoreStackTrace =
  212. ex is SocketException
  213. || ex is IOException
  214. || ex is OperationCanceledException
  215. || ex is SecurityException
  216. || ex is AuthenticationException
  217. || ex is FileNotFoundException;
  218. if (ignoreStackTrace)
  219. {
  220. _logger.LogError("Error processing request: {Message}. URL: {Url}", ex.Message.TrimEnd('.'), urlToLog);
  221. }
  222. else
  223. {
  224. _logger.LogError(ex, "Error processing request. URL: {Url}", urlToLog);
  225. }
  226. var httpRes = httpReq.Response;
  227. if (httpRes.HasStarted)
  228. {
  229. return;
  230. }
  231. httpRes.StatusCode = statusCode;
  232. var errContent = NormalizeExceptionMessage(ex.Message);
  233. httpRes.ContentType = "text/plain";
  234. httpRes.ContentLength = errContent.Length;
  235. await httpRes.WriteAsync(errContent).ConfigureAwait(false);
  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 requestEx)
  459. {
  460. try
  461. {
  462. var requestInnerEx = GetActualException(requestEx);
  463. var statusCode = GetStatusCode(requestInnerEx);
  464. // Do not handle 500 server exceptions manually when in development mode
  465. // The framework-defined development exception page will be returned instead
  466. if (statusCode == 500 && _hostEnvironment.IsDevelopment())
  467. {
  468. throw;
  469. }
  470. await ErrorHandler(requestInnerEx, httpReq, statusCode, urlToLog).ConfigureAwait(false);
  471. }
  472. catch (Exception handlerException)
  473. {
  474. var aggregateEx = new AggregateException("Error while handling request exception", requestEx, handlerException);
  475. _logger.LogError(aggregateEx, "Error while handling exception in response to {Url}", urlToLog);
  476. if (_hostEnvironment.IsDevelopment())
  477. {
  478. throw aggregateEx;
  479. }
  480. }
  481. }
  482. finally
  483. {
  484. if (httpRes.StatusCode >= 500)
  485. {
  486. _logger.LogDebug("Sending HTTP Response 500 in response to {Url}", urlToLog);
  487. }
  488. stopWatch.Stop();
  489. var elapsed = stopWatch.Elapsed;
  490. if (elapsed.TotalMilliseconds > 500)
  491. {
  492. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  493. }
  494. }
  495. }
  496. // Entry point for HttpListener
  497. public ServiceHandler GetServiceHandler(IHttpRequest httpReq)
  498. {
  499. var pathInfo = httpReq.PathInfo;
  500. pathInfo = ServiceHandler.GetSanitizedPathInfo(pathInfo, out string contentType);
  501. var restPath = ServiceController.GetRestPathForRequest(httpReq.HttpMethod, pathInfo);
  502. if (restPath != null)
  503. {
  504. return new ServiceHandler(restPath, contentType);
  505. }
  506. _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
  507. return null;
  508. }
  509. private void RedirectToSecureUrl(IHttpRequest httpReq, HttpResponse httpRes, string url)
  510. {
  511. if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
  512. {
  513. var builder = new UriBuilder(uri)
  514. {
  515. Port = _config.Configuration.PublicHttpsPort,
  516. Scheme = "https"
  517. };
  518. url = builder.Uri.ToString();
  519. }
  520. httpRes.Redirect(url);
  521. }
  522. /// <summary>
  523. /// Adds the rest handlers.
  524. /// </summary>
  525. /// <param name="serviceTypes">The service types to register with the <see cref="ServiceController"/>.</param>
  526. /// <param name="listeners">The web socket listeners.</param>
  527. /// <param name="urlPrefixes">The URL prefixes. See <see cref="UrlPrefixes"/>.</param>
  528. public void Init(IEnumerable<Type> serviceTypes, IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
  529. {
  530. _webSocketListeners = listeners.ToArray();
  531. UrlPrefixes = urlPrefixes.ToArray();
  532. ServiceController.Init(this, serviceTypes);
  533. ResponseFilters = new Action<IRequest, HttpResponse, object>[]
  534. {
  535. new ResponseFilter(_logger).FilterResponse
  536. };
  537. }
  538. public RouteAttribute[] GetRouteAttributes(Type requestType)
  539. {
  540. var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
  541. var clone = routes.ToList();
  542. foreach (var route in clone)
  543. {
  544. routes.Add(new RouteAttribute(NormalizeCustomRoutePath(route.Path), route.Verbs)
  545. {
  546. Notes = route.Notes,
  547. Priority = route.Priority,
  548. Summary = route.Summary
  549. });
  550. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  551. {
  552. Notes = route.Notes,
  553. Priority = route.Priority,
  554. Summary = route.Summary
  555. });
  556. routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
  557. {
  558. Notes = route.Notes,
  559. Priority = route.Priority,
  560. Summary = route.Summary
  561. });
  562. }
  563. return routes.ToArray();
  564. }
  565. public Func<string, object> GetParseFn(Type propertyType)
  566. {
  567. return _funcParseFn(propertyType);
  568. }
  569. public void SerializeToJson(object o, Stream stream)
  570. {
  571. _jsonSerializer.SerializeToStream(o, stream);
  572. }
  573. public void SerializeToXml(object o, Stream stream)
  574. {
  575. _xmlSerializer.SerializeToStream(o, stream);
  576. }
  577. public Task<object> DeserializeXml(Type type, Stream stream)
  578. {
  579. return Task.FromResult(_xmlSerializer.DeserializeFromStream(type, stream));
  580. }
  581. public Task<object> DeserializeJson(Type type, Stream stream)
  582. {
  583. return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
  584. }
  585. public Task ProcessWebSocketRequest(HttpContext context)
  586. {
  587. return _socketListener.ProcessWebSocketRequest(context);
  588. }
  589. private string NormalizeEmbyRoutePath(string path)
  590. {
  591. _logger.LogDebug("Normalizing /emby route");
  592. return _baseUrlPrefix + "/emby" + NormalizeUrlPath(path);
  593. }
  594. private string NormalizeMediaBrowserRoutePath(string path)
  595. {
  596. _logger.LogDebug("Normalizing /mediabrowser route");
  597. return _baseUrlPrefix + "/mediabrowser" + NormalizeUrlPath(path);
  598. }
  599. private string NormalizeCustomRoutePath(string path)
  600. {
  601. _logger.LogDebug("Normalizing custom route {0}", path);
  602. return _baseUrlPrefix + NormalizeUrlPath(path);
  603. }
  604. /// <inheritdoc />
  605. public void Dispose()
  606. {
  607. Dispose(true);
  608. GC.SuppressFinalize(this);
  609. }
  610. protected virtual void Dispose(bool disposing)
  611. {
  612. if (_disposed)
  613. {
  614. return;
  615. }
  616. if (disposing)
  617. {
  618. Stop();
  619. }
  620. _disposed = true;
  621. }
  622. /// <summary>
  623. /// Processes the web socket message received.
  624. /// </summary>
  625. /// <param name="result">The result.</param>
  626. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  627. {
  628. if (_disposed)
  629. {
  630. return Task.CompletedTask;
  631. }
  632. _logger.LogDebug("Websocket message received: {0}", result.MessageType);
  633. IEnumerable<Task> GetTasks()
  634. {
  635. foreach (var x in _webSocketListeners)
  636. {
  637. yield return x.ProcessMessageAsync(result);
  638. }
  639. }
  640. return Task.WhenAll(GetTasks());
  641. }
  642. }
  643. }