HttpListenerHost.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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) ?? string.Empty;
  233. httpRes.ContentType = "text/plain";
  234. httpRes.ContentLength = errContent.Length;
  235. await httpRes.WriteAsync(errContent).ConfigureAwait(false);
  236. }
  237. private string NormalizeExceptionMessage(Exception ex)
  238. {
  239. // Do not expose the exception message for AuthenticationException
  240. if (ex is AuthenticationException)
  241. {
  242. return null;
  243. }
  244. // Strip any information we don't want to reveal
  245. return ex.Message
  246. ?.Replace(_config.ApplicationPaths.ProgramSystemPath, string.Empty, StringComparison.OrdinalIgnoreCase)
  247. .Replace(_config.ApplicationPaths.ProgramDataPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  248. }
  249. /// <summary>
  250. /// Shut down the Web Service
  251. /// </summary>
  252. public void Stop()
  253. {
  254. List<IWebSocketConnection> connections;
  255. lock (_webSocketConnections)
  256. {
  257. connections = _webSocketConnections.ToList();
  258. _webSocketConnections.Clear();
  259. }
  260. foreach (var connection in connections)
  261. {
  262. try
  263. {
  264. connection.Dispose();
  265. }
  266. catch (Exception ex)
  267. {
  268. _logger.LogError(ex, "Error disposing connection");
  269. }
  270. }
  271. }
  272. public static string RemoveQueryStringByKey(string url, string key)
  273. {
  274. var uri = new Uri(url);
  275. // this gets all the query string key value pairs as a collection
  276. var newQueryString = QueryHelpers.ParseQuery(uri.Query);
  277. var originalCount = newQueryString.Count;
  278. if (originalCount == 0)
  279. {
  280. return url;
  281. }
  282. // this removes the key if exists
  283. newQueryString.Remove(key);
  284. if (originalCount == newQueryString.Count)
  285. {
  286. return url;
  287. }
  288. // this gets the page path from root without QueryString
  289. string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
  290. return newQueryString.Count > 0
  291. ? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
  292. : pagePathWithoutQueryString;
  293. }
  294. private static string GetUrlToLog(string url)
  295. {
  296. url = RemoveQueryStringByKey(url, "api_key");
  297. return url;
  298. }
  299. private static string NormalizeConfiguredLocalAddress(string address)
  300. {
  301. var add = address.AsSpan().Trim('/');
  302. int index = add.IndexOf('/');
  303. if (index != -1)
  304. {
  305. add = add.Slice(index + 1);
  306. }
  307. return add.TrimStart('/').ToString();
  308. }
  309. private bool ValidateHost(string host)
  310. {
  311. var hosts = _config
  312. .Configuration
  313. .LocalNetworkAddresses
  314. .Select(NormalizeConfiguredLocalAddress)
  315. .ToList();
  316. if (hosts.Count == 0)
  317. {
  318. return true;
  319. }
  320. host ??= string.Empty;
  321. if (_networkManager.IsInPrivateAddressSpace(host))
  322. {
  323. hosts.Add("localhost");
  324. hosts.Add("127.0.0.1");
  325. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  326. }
  327. return true;
  328. }
  329. private bool ValidateRequest(string remoteIp, bool isLocal)
  330. {
  331. if (isLocal)
  332. {
  333. return true;
  334. }
  335. if (_config.Configuration.EnableRemoteAccess)
  336. {
  337. var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  338. if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
  339. {
  340. if (_config.Configuration.IsRemoteIPFilterBlacklist)
  341. {
  342. return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  343. }
  344. else
  345. {
  346. return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  347. }
  348. }
  349. }
  350. else
  351. {
  352. if (!_networkManager.IsInLocalNetwork(remoteIp))
  353. {
  354. return false;
  355. }
  356. }
  357. return true;
  358. }
  359. private bool ValidateSsl(string remoteIp, string urlString)
  360. {
  361. if (_config.Configuration.RequireHttps && _appHost.EnableHttps && !_config.Configuration.IsBehindProxy)
  362. {
  363. if (urlString.IndexOf("https://", StringComparison.OrdinalIgnoreCase) == -1)
  364. {
  365. // These are hacks, but if these ever occur on ipv6 in the local network they could be incorrectly redirected
  366. if (urlString.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) != -1
  367. || urlString.IndexOf("dlna/", StringComparison.OrdinalIgnoreCase) != -1)
  368. {
  369. return true;
  370. }
  371. if (!_networkManager.IsInLocalNetwork(remoteIp))
  372. {
  373. return false;
  374. }
  375. }
  376. }
  377. return true;
  378. }
  379. /// <summary>
  380. /// Overridable method that can be used to implement a custom handler.
  381. /// </summary>
  382. public async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
  383. {
  384. var stopWatch = new Stopwatch();
  385. stopWatch.Start();
  386. var httpRes = httpReq.Response;
  387. string urlToLog = GetUrlToLog(urlString);
  388. string remoteIp = httpReq.RemoteIp;
  389. try
  390. {
  391. if (_disposed)
  392. {
  393. httpRes.StatusCode = 503;
  394. httpRes.ContentType = "text/plain";
  395. await httpRes.WriteAsync("Server shutting down", cancellationToken).ConfigureAwait(false);
  396. return;
  397. }
  398. if (!ValidateHost(host))
  399. {
  400. httpRes.StatusCode = 400;
  401. httpRes.ContentType = "text/plain";
  402. await httpRes.WriteAsync("Invalid host", cancellationToken).ConfigureAwait(false);
  403. return;
  404. }
  405. if (!ValidateRequest(remoteIp, httpReq.IsLocal))
  406. {
  407. httpRes.StatusCode = 403;
  408. httpRes.ContentType = "text/plain";
  409. await httpRes.WriteAsync("Forbidden", cancellationToken).ConfigureAwait(false);
  410. return;
  411. }
  412. if (!ValidateSsl(httpReq.RemoteIp, urlString))
  413. {
  414. RedirectToSecureUrl(httpReq, httpRes, urlString);
  415. return;
  416. }
  417. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  418. {
  419. httpRes.StatusCode = 200;
  420. httpRes.Headers.Add("Access-Control-Allow-Origin", "*");
  421. httpRes.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  422. httpRes.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
  423. httpRes.ContentType = "text/plain";
  424. await httpRes.WriteAsync(string.Empty, cancellationToken).ConfigureAwait(false);
  425. return;
  426. }
  427. if (string.Equals(localPath, _baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase)
  428. || string.Equals(localPath, _baseUrlPrefix, StringComparison.OrdinalIgnoreCase)
  429. || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)
  430. || string.IsNullOrEmpty(localPath)
  431. || !localPath.StartsWith(_baseUrlPrefix, StringComparison.OrdinalIgnoreCase))
  432. {
  433. // Always redirect back to the default path if the base prefix is invalid or missing
  434. _logger.LogDebug("Normalizing a URL at {0}", localPath);
  435. httpRes.Redirect(_baseUrlPrefix + "/" + _defaultRedirectPath);
  436. return;
  437. }
  438. if (!string.IsNullOrEmpty(GlobalResponse))
  439. {
  440. // We don't want the address pings in ApplicationHost to fail
  441. if (localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  442. {
  443. httpRes.StatusCode = 503;
  444. httpRes.ContentType = "text/html";
  445. await httpRes.WriteAsync(GlobalResponse, cancellationToken).ConfigureAwait(false);
  446. return;
  447. }
  448. }
  449. var handler = GetServiceHandler(httpReq);
  450. if (handler != null)
  451. {
  452. await handler.ProcessRequestAsync(this, httpReq, httpRes, _logger, cancellationToken).ConfigureAwait(false);
  453. }
  454. else
  455. {
  456. throw new FileNotFoundException();
  457. }
  458. }
  459. catch (Exception requestEx)
  460. {
  461. try
  462. {
  463. var requestInnerEx = GetActualException(requestEx);
  464. var statusCode = GetStatusCode(requestInnerEx);
  465. // Do not handle 500 server exceptions manually when in development mode
  466. // The framework-defined development exception page will be returned instead
  467. if (statusCode == 500 && _hostEnvironment.IsDevelopment())
  468. {
  469. throw;
  470. }
  471. await ErrorHandler(requestInnerEx, httpReq, statusCode, urlToLog).ConfigureAwait(false);
  472. }
  473. catch (Exception handlerException)
  474. {
  475. var aggregateEx = new AggregateException("Error while handling request exception", requestEx, handlerException);
  476. _logger.LogError(aggregateEx, "Error while handling exception in response to {Url}", urlToLog);
  477. if (_hostEnvironment.IsDevelopment())
  478. {
  479. throw aggregateEx;
  480. }
  481. }
  482. }
  483. finally
  484. {
  485. if (httpRes.StatusCode >= 500)
  486. {
  487. _logger.LogDebug("Sending HTTP Response 500 in response to {Url}", urlToLog);
  488. }
  489. stopWatch.Stop();
  490. var elapsed = stopWatch.Elapsed;
  491. if (elapsed.TotalMilliseconds > 500)
  492. {
  493. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  494. }
  495. }
  496. }
  497. // Entry point for HttpListener
  498. public ServiceHandler GetServiceHandler(IHttpRequest httpReq)
  499. {
  500. var pathInfo = httpReq.PathInfo;
  501. pathInfo = ServiceHandler.GetSanitizedPathInfo(pathInfo, out string contentType);
  502. var restPath = ServiceController.GetRestPathForRequest(httpReq.HttpMethod, pathInfo);
  503. if (restPath != null)
  504. {
  505. return new ServiceHandler(restPath, contentType);
  506. }
  507. _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
  508. return null;
  509. }
  510. private void RedirectToSecureUrl(IHttpRequest httpReq, HttpResponse httpRes, string url)
  511. {
  512. if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
  513. {
  514. var builder = new UriBuilder(uri)
  515. {
  516. Port = _config.Configuration.PublicHttpsPort,
  517. Scheme = "https"
  518. };
  519. url = builder.Uri.ToString();
  520. }
  521. httpRes.Redirect(url);
  522. }
  523. /// <summary>
  524. /// Adds the rest handlers.
  525. /// </summary>
  526. /// <param name="serviceTypes">The service types to register with the <see cref="ServiceController"/>.</param>
  527. /// <param name="listeners">The web socket listeners.</param>
  528. /// <param name="urlPrefixes">The URL prefixes. See <see cref="UrlPrefixes"/>.</param>
  529. public void Init(IEnumerable<Type> serviceTypes, IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
  530. {
  531. _webSocketListeners = listeners.ToArray();
  532. UrlPrefixes = urlPrefixes.ToArray();
  533. ServiceController.Init(this, serviceTypes);
  534. ResponseFilters = new Action<IRequest, HttpResponse, object>[]
  535. {
  536. new ResponseFilter(_logger).FilterResponse
  537. };
  538. }
  539. public RouteAttribute[] GetRouteAttributes(Type requestType)
  540. {
  541. var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
  542. var clone = routes.ToList();
  543. foreach (var route in clone)
  544. {
  545. routes.Add(new RouteAttribute(NormalizeCustomRoutePath(route.Path), route.Verbs)
  546. {
  547. Notes = route.Notes,
  548. Priority = route.Priority,
  549. Summary = route.Summary
  550. });
  551. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  552. {
  553. Notes = route.Notes,
  554. Priority = route.Priority,
  555. Summary = route.Summary
  556. });
  557. routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
  558. {
  559. Notes = route.Notes,
  560. Priority = route.Priority,
  561. Summary = route.Summary
  562. });
  563. }
  564. return routes.ToArray();
  565. }
  566. public Func<string, object> GetParseFn(Type propertyType)
  567. {
  568. return _funcParseFn(propertyType);
  569. }
  570. public void SerializeToJson(object o, Stream stream)
  571. {
  572. _jsonSerializer.SerializeToStream(o, stream);
  573. }
  574. public void SerializeToXml(object o, Stream stream)
  575. {
  576. _xmlSerializer.SerializeToStream(o, stream);
  577. }
  578. public Task<object> DeserializeXml(Type type, Stream stream)
  579. {
  580. return Task.FromResult(_xmlSerializer.DeserializeFromStream(type, stream));
  581. }
  582. public Task<object> DeserializeJson(Type type, Stream stream)
  583. {
  584. return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
  585. }
  586. public Task ProcessWebSocketRequest(HttpContext context)
  587. {
  588. return _socketListener.ProcessWebSocketRequest(context);
  589. }
  590. private string NormalizeEmbyRoutePath(string path)
  591. {
  592. _logger.LogDebug("Normalizing /emby route");
  593. return _baseUrlPrefix + "/emby" + NormalizeUrlPath(path);
  594. }
  595. private string NormalizeMediaBrowserRoutePath(string path)
  596. {
  597. _logger.LogDebug("Normalizing /mediabrowser route");
  598. return _baseUrlPrefix + "/mediabrowser" + NormalizeUrlPath(path);
  599. }
  600. private string NormalizeCustomRoutePath(string path)
  601. {
  602. _logger.LogDebug("Normalizing custom route {0}", path);
  603. return _baseUrlPrefix + NormalizeUrlPath(path);
  604. }
  605. /// <inheritdoc />
  606. public void Dispose()
  607. {
  608. Dispose(true);
  609. GC.SuppressFinalize(this);
  610. }
  611. protected virtual void Dispose(bool disposing)
  612. {
  613. if (_disposed)
  614. {
  615. return;
  616. }
  617. if (disposing)
  618. {
  619. Stop();
  620. }
  621. _disposed = true;
  622. }
  623. /// <summary>
  624. /// Processes the web socket message received.
  625. /// </summary>
  626. /// <param name="result">The result.</param>
  627. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  628. {
  629. if (_disposed)
  630. {
  631. return Task.CompletedTask;
  632. }
  633. _logger.LogDebug("Websocket message received: {0}", result.MessageType);
  634. IEnumerable<Task> GetTasks()
  635. {
  636. foreach (var x in _webSocketListeners)
  637. {
  638. yield return x.ProcessMessageAsync(result);
  639. }
  640. }
  641. return Task.WhenAll(GetTasks());
  642. }
  643. }
  644. }