HttpListenerHost.cs 28 KB

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