HttpListenerHost.cs 28 KB

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