HttpListenerHost.cs 29 KB

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