ApplicationHost.cs 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Net.Sockets;
  12. using System.Reflection;
  13. using System.Runtime.InteropServices;
  14. using System.Security.Cryptography.X509Certificates;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using Emby.Dlna;
  19. using Emby.Dlna.Main;
  20. using Emby.Dlna.Ssdp;
  21. using Emby.Drawing;
  22. using Emby.Notifications;
  23. using Emby.Photos;
  24. using Emby.Server.Implementations.Activity;
  25. using Emby.Server.Implementations.Archiving;
  26. using Emby.Server.Implementations.Channels;
  27. using Emby.Server.Implementations.Collections;
  28. using Emby.Server.Implementations.Configuration;
  29. using Emby.Server.Implementations.Cryptography;
  30. using Emby.Server.Implementations.Data;
  31. using Emby.Server.Implementations.Devices;
  32. using Emby.Server.Implementations.Dto;
  33. using Emby.Server.Implementations.HttpServer;
  34. using Emby.Server.Implementations.HttpServer.Security;
  35. using Emby.Server.Implementations.IO;
  36. using Emby.Server.Implementations.Library;
  37. using Emby.Server.Implementations.LiveTv;
  38. using Emby.Server.Implementations.Localization;
  39. using Emby.Server.Implementations.Net;
  40. using Emby.Server.Implementations.Playlists;
  41. using Emby.Server.Implementations.ScheduledTasks;
  42. using Emby.Server.Implementations.Security;
  43. using Emby.Server.Implementations.Serialization;
  44. using Emby.Server.Implementations.Services;
  45. using Emby.Server.Implementations.Session;
  46. using Emby.Server.Implementations.SocketSharp;
  47. using Emby.Server.Implementations.TV;
  48. using Emby.Server.Implementations.Updates;
  49. using Emby.Server.Implementations.Syncplay;
  50. using MediaBrowser.Api;
  51. using MediaBrowser.Common;
  52. using MediaBrowser.Common.Configuration;
  53. using MediaBrowser.Common.Events;
  54. using MediaBrowser.Common.Net;
  55. using MediaBrowser.Common.Plugins;
  56. using MediaBrowser.Common.Updates;
  57. using MediaBrowser.Controller;
  58. using MediaBrowser.Controller.Authentication;
  59. using MediaBrowser.Controller.Channels;
  60. using MediaBrowser.Controller.Chapters;
  61. using MediaBrowser.Controller.Collections;
  62. using MediaBrowser.Controller.Configuration;
  63. using MediaBrowser.Controller.Devices;
  64. using MediaBrowser.Controller.Dlna;
  65. using MediaBrowser.Controller.Drawing;
  66. using MediaBrowser.Controller.Dto;
  67. using MediaBrowser.Controller.Entities;
  68. using MediaBrowser.Controller.Library;
  69. using MediaBrowser.Controller.LiveTv;
  70. using MediaBrowser.Controller.MediaEncoding;
  71. using MediaBrowser.Controller.Net;
  72. using MediaBrowser.Controller.Notifications;
  73. using MediaBrowser.Controller.Persistence;
  74. using MediaBrowser.Controller.Playlists;
  75. using MediaBrowser.Controller.Plugins;
  76. using MediaBrowser.Controller.Providers;
  77. using MediaBrowser.Controller.Resolvers;
  78. using MediaBrowser.Controller.Security;
  79. using MediaBrowser.Controller.Session;
  80. using MediaBrowser.Controller.Sorting;
  81. using MediaBrowser.Controller.Subtitles;
  82. using MediaBrowser.Controller.TV;
  83. using MediaBrowser.Controller.Syncplay;
  84. using MediaBrowser.LocalMetadata.Savers;
  85. using MediaBrowser.MediaEncoding.BdInfo;
  86. using MediaBrowser.Model.Activity;
  87. using MediaBrowser.Model.Configuration;
  88. using MediaBrowser.Model.Cryptography;
  89. using MediaBrowser.Model.Dlna;
  90. using MediaBrowser.Model.Globalization;
  91. using MediaBrowser.Model.IO;
  92. using MediaBrowser.Model.MediaInfo;
  93. using MediaBrowser.Model.Net;
  94. using MediaBrowser.Model.Serialization;
  95. using MediaBrowser.Model.Services;
  96. using MediaBrowser.Model.System;
  97. using MediaBrowser.Model.Tasks;
  98. using MediaBrowser.Model.Updates;
  99. using MediaBrowser.Providers.Chapters;
  100. using MediaBrowser.Providers.Manager;
  101. using MediaBrowser.Providers.Plugins.TheTvdb;
  102. using MediaBrowser.Providers.Subtitles;
  103. using MediaBrowser.WebDashboard.Api;
  104. using MediaBrowser.XbmcMetadata.Providers;
  105. using Microsoft.AspNetCore.Http;
  106. using Microsoft.AspNetCore.Http.Extensions;
  107. using Microsoft.Extensions.DependencyInjection;
  108. using Microsoft.Extensions.Logging;
  109. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  110. namespace Emby.Server.Implementations
  111. {
  112. /// <summary>
  113. /// Class CompositionRoot.
  114. /// </summary>
  115. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  116. {
  117. /// <summary>
  118. /// The environment variable prefixes to log at server startup.
  119. /// </summary>
  120. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  121. private readonly IFileSystem _fileSystemManager;
  122. private readonly INetworkManager _networkManager;
  123. private readonly IXmlSerializer _xmlSerializer;
  124. private readonly IStartupOptions _startupOptions;
  125. private IMediaEncoder _mediaEncoder;
  126. private ISessionManager _sessionManager;
  127. private IHttpServer _httpServer;
  128. private IHttpClient _httpClient;
  129. /// <summary>
  130. /// Gets a value indicating whether this instance can self restart.
  131. /// </summary>
  132. public bool CanSelfRestart => _startupOptions.RestartPath != null;
  133. public virtual bool CanLaunchWebBrowser
  134. {
  135. get
  136. {
  137. if (!Environment.UserInteractive)
  138. {
  139. return false;
  140. }
  141. if (_startupOptions.IsService)
  142. {
  143. return false;
  144. }
  145. if (OperatingSystem.Id == OperatingSystemId.Windows
  146. || OperatingSystem.Id == OperatingSystemId.Darwin)
  147. {
  148. return true;
  149. }
  150. return false;
  151. }
  152. }
  153. /// <summary>
  154. /// Occurs when [has pending restart changed].
  155. /// </summary>
  156. public event EventHandler HasPendingRestartChanged;
  157. /// <summary>
  158. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  159. /// </summary>
  160. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  161. public bool HasPendingRestart { get; private set; }
  162. /// <inheritdoc />
  163. public bool IsShuttingDown { get; private set; }
  164. /// <summary>
  165. /// Gets the logger.
  166. /// </summary>
  167. protected ILogger Logger { get; }
  168. private IPlugin[] _plugins;
  169. /// <summary>
  170. /// Gets the plugins.
  171. /// </summary>
  172. /// <value>The plugins.</value>
  173. public IReadOnlyList<IPlugin> Plugins => _plugins;
  174. /// <summary>
  175. /// Gets the logger factory.
  176. /// </summary>
  177. protected ILoggerFactory LoggerFactory { get; }
  178. /// <summary>
  179. /// Gets or sets the application paths.
  180. /// </summary>
  181. /// <value>The application paths.</value>
  182. protected ServerApplicationPaths ApplicationPaths { get; set; }
  183. /// <summary>
  184. /// Gets or sets all concrete types.
  185. /// </summary>
  186. /// <value>All concrete types.</value>
  187. private Type[] _allConcreteTypes;
  188. /// <summary>
  189. /// The disposable parts.
  190. /// </summary>
  191. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  192. /// <summary>
  193. /// Gets the configuration manager.
  194. /// </summary>
  195. /// <value>The configuration manager.</value>
  196. protected IConfigurationManager ConfigurationManager { get; set; }
  197. /// <summary>
  198. /// Gets or sets the service provider.
  199. /// </summary>
  200. public IServiceProvider ServiceProvider { get; set; }
  201. /// <summary>
  202. /// Gets the http port for the webhost.
  203. /// </summary>
  204. public int HttpPort { get; private set; }
  205. /// <summary>
  206. /// Gets the https port for the webhost.
  207. /// </summary>
  208. public int HttpsPort { get; private set; }
  209. /// <summary>
  210. /// Gets the server configuration manager.
  211. /// </summary>
  212. /// <value>The server configuration manager.</value>
  213. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  214. /// <summary>
  215. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  216. /// </summary>
  217. public ApplicationHost(
  218. ServerApplicationPaths applicationPaths,
  219. ILoggerFactory loggerFactory,
  220. IStartupOptions options,
  221. IFileSystem fileSystem,
  222. INetworkManager networkManager)
  223. {
  224. _xmlSerializer = new MyXmlSerializer();
  225. _networkManager = networkManager;
  226. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  227. ApplicationPaths = applicationPaths;
  228. LoggerFactory = loggerFactory;
  229. _fileSystemManager = fileSystem;
  230. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
  231. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  232. _startupOptions = options;
  233. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  234. _networkManager.NetworkChanged += OnNetworkChanged;
  235. CertificateInfo = new CertificateInfo
  236. {
  237. Path = ServerConfigurationManager.Configuration.CertificatePath,
  238. Password = ServerConfigurationManager.Configuration.CertificatePassword
  239. };
  240. Certificate = GetCertificate(CertificateInfo);
  241. }
  242. public string ExpandVirtualPath(string path)
  243. {
  244. var appPaths = ApplicationPaths;
  245. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  246. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  247. }
  248. public string ReverseVirtualPath(string path)
  249. {
  250. var appPaths = ApplicationPaths;
  251. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  252. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  253. }
  254. private string[] GetConfiguredLocalSubnets()
  255. {
  256. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  257. }
  258. private void OnNetworkChanged(object sender, EventArgs e)
  259. {
  260. _validAddressResults.Clear();
  261. }
  262. /// <inheritdoc />
  263. public Version ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version;
  264. /// <inheritdoc />
  265. public string ApplicationVersionString { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
  266. /// <summary>
  267. /// Gets the current application user agent.
  268. /// </summary>
  269. /// <value>The application user agent.</value>
  270. public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  271. /// <summary>
  272. /// Gets the email address for use within a comment section of a user agent field.
  273. /// Presently used to provide contact information to MusicBrainz service.
  274. /// </summary>
  275. public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
  276. /// <summary>
  277. /// Gets the current application name.
  278. /// </summary>
  279. /// <value>The application name.</value>
  280. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  281. private DeviceId _deviceId;
  282. public string SystemId
  283. {
  284. get
  285. {
  286. if (_deviceId == null)
  287. {
  288. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  289. }
  290. return _deviceId.Value;
  291. }
  292. }
  293. /// <inheritdoc/>
  294. public string Name => ApplicationProductName;
  295. /// <summary>
  296. /// Creates an instance of type and resolves all constructor dependencies.
  297. /// </summary>
  298. /// <param name="type">The type.</param>
  299. /// <returns>System.Object.</returns>
  300. public object CreateInstance(Type type)
  301. => ActivatorUtilities.CreateInstance(ServiceProvider, type);
  302. /// <summary>
  303. /// Creates an instance of type and resolves all constructor dependencies.
  304. /// </summary>
  305. /// /// <typeparam name="T">The type.</typeparam>
  306. /// <returns>T.</returns>
  307. public T CreateInstance<T>()
  308. => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
  309. /// <summary>
  310. /// Creates the instance safe.
  311. /// </summary>
  312. /// <param name="type">The type.</param>
  313. /// <returns>System.Object.</returns>
  314. protected object CreateInstanceSafe(Type type)
  315. {
  316. try
  317. {
  318. Logger.LogDebug("Creating instance of {Type}", type);
  319. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  320. }
  321. catch (Exception ex)
  322. {
  323. Logger.LogError(ex, "Error creating {Type}", type);
  324. return null;
  325. }
  326. }
  327. /// <summary>
  328. /// Resolves this instance.
  329. /// </summary>
  330. /// <typeparam name="T">The type</typeparam>
  331. /// <returns>``0.</returns>
  332. public T Resolve<T>() => ServiceProvider.GetService<T>();
  333. /// <summary>
  334. /// Gets the export types.
  335. /// </summary>
  336. /// <typeparam name="T">The type.</typeparam>
  337. /// <returns>IEnumerable{Type}.</returns>
  338. public IEnumerable<Type> GetExportTypes<T>()
  339. {
  340. var currentType = typeof(T);
  341. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  342. }
  343. /// <inheritdoc />
  344. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  345. {
  346. // Convert to list so this isn't executed for each iteration
  347. var parts = GetExportTypes<T>()
  348. .Select(CreateInstanceSafe)
  349. .Where(i => i != null)
  350. .Cast<T>()
  351. .ToList();
  352. if (manageLifetime)
  353. {
  354. lock (_disposableParts)
  355. {
  356. _disposableParts.AddRange(parts.OfType<IDisposable>());
  357. }
  358. }
  359. return parts;
  360. }
  361. /// <summary>
  362. /// Runs the startup tasks.
  363. /// </summary>
  364. /// <returns><see cref="Task" />.</returns>
  365. public async Task RunStartupTasksAsync()
  366. {
  367. Logger.LogInformation("Running startup tasks");
  368. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  369. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  370. _mediaEncoder.SetFFmpegPath();
  371. Logger.LogInformation("ServerId: {0}", SystemId);
  372. var entryPoints = GetExports<IServerEntryPoint>();
  373. var stopWatch = new Stopwatch();
  374. stopWatch.Start();
  375. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  376. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  377. Logger.LogInformation("Core startup complete");
  378. _httpServer.GlobalResponse = null;
  379. stopWatch.Restart();
  380. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  381. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  382. stopWatch.Stop();
  383. }
  384. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  385. {
  386. foreach (var entryPoint in entryPoints)
  387. {
  388. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  389. {
  390. continue;
  391. }
  392. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  393. yield return entryPoint.RunAsync();
  394. }
  395. }
  396. /// <inheritdoc/>
  397. public void Init(IServiceCollection serviceCollection)
  398. {
  399. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  400. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  401. // Safeguard against invalid configuration
  402. if (HttpPort == HttpsPort)
  403. {
  404. HttpPort = ServerConfiguration.DefaultHttpPort;
  405. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  406. }
  407. if (Plugins != null)
  408. {
  409. var pluginBuilder = new StringBuilder();
  410. foreach (var plugin in Plugins)
  411. {
  412. pluginBuilder.AppendLine(
  413. string.Format(
  414. CultureInfo.InvariantCulture,
  415. "{0} {1}",
  416. plugin.Name,
  417. plugin.Version));
  418. }
  419. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  420. }
  421. DiscoverTypes();
  422. RegisterServices(serviceCollection);
  423. }
  424. public async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func<Task> next)
  425. {
  426. if (!context.WebSockets.IsWebSocketRequest)
  427. {
  428. await next().ConfigureAwait(false);
  429. return;
  430. }
  431. await _httpServer.ProcessWebSocketRequest(context).ConfigureAwait(false);
  432. }
  433. public async Task ExecuteHttpHandlerAsync(HttpContext context, Func<Task> next)
  434. {
  435. if (context.WebSockets.IsWebSocketRequest)
  436. {
  437. await next().ConfigureAwait(false);
  438. return;
  439. }
  440. var request = context.Request;
  441. var response = context.Response;
  442. var localPath = context.Request.Path.ToString();
  443. var req = new WebSocketSharpRequest(request, response, request.Path, LoggerFactory.CreateLogger<WebSocketSharpRequest>());
  444. await _httpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted).ConfigureAwait(false);
  445. }
  446. /// <summary>
  447. /// Registers services/resources with the service collection that will be available via DI.
  448. /// </summary>
  449. protected virtual void RegisterServices(IServiceCollection serviceCollection)
  450. {
  451. serviceCollection.AddSingleton(_startupOptions);
  452. serviceCollection.AddMemoryCache();
  453. serviceCollection.AddSingleton(ConfigurationManager);
  454. serviceCollection.AddSingleton<IApplicationHost>(this);
  455. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  456. serviceCollection.AddSingleton<IJsonSerializer, JsonSerializer>();
  457. // TODO: Remove support for injecting ILogger completely
  458. serviceCollection.AddSingleton((provider) =>
  459. {
  460. Logger.LogWarning("Injecting ILogger directly is deprecated and should be replaced with ILogger<T>");
  461. return Logger;
  462. });
  463. serviceCollection.AddSingleton(_fileSystemManager);
  464. serviceCollection.AddSingleton<TvdbClientManager>();
  465. serviceCollection.AddSingleton<IHttpClient, HttpClientManager.HttpClientManager>();
  466. serviceCollection.AddSingleton(_networkManager);
  467. serviceCollection.AddSingleton<IIsoManager, IsoManager>();
  468. serviceCollection.AddSingleton<ITaskManager, TaskManager>();
  469. serviceCollection.AddSingleton(_xmlSerializer);
  470. serviceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  471. serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  472. serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  473. serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  474. serviceCollection.AddSingleton<IZipClient, ZipClient>();
  475. serviceCollection.AddSingleton<IHttpResultFactory, HttpResultFactory>();
  476. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  477. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  478. serviceCollection.AddSingleton(ServerConfigurationManager);
  479. serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  480. serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  481. serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  482. serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  483. serviceCollection.AddSingleton<IDisplayPreferencesRepository, SqliteDisplayPreferencesRepository>();
  484. serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  485. serviceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  486. serviceCollection.AddSingleton<IUserRepository, SqliteUserRepository>();
  487. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  488. serviceCollection.AddTransient(provider => new Lazy<IDtoService>(provider.GetRequiredService<IDtoService>));
  489. serviceCollection.AddSingleton<IUserManager, UserManager>();
  490. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  491. // TODO: Add StartupOptions.FFmpegPath to IConfiguration and remove this custom activation
  492. serviceCollection.AddTransient(provider => new Lazy<EncodingHelper>(provider.GetRequiredService<EncodingHelper>));
  493. serviceCollection.AddSingleton<IMediaEncoder>(provider =>
  494. ActivatorUtilities.CreateInstance<MediaBrowser.MediaEncoding.Encoder.MediaEncoder>(provider, _startupOptions.FFmpegPath ?? string.Empty));
  495. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  496. serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  497. serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  498. serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  499. serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  500. serviceCollection.AddSingleton<IMusicManager, MusicManager>();
  501. serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  502. serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  503. serviceCollection.AddSingleton<ServiceController>();
  504. serviceCollection.AddSingleton<IHttpListener, WebSocketSharpListener>();
  505. serviceCollection.AddSingleton<IHttpServer, HttpListenerHost>();
  506. serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  507. serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  508. serviceCollection.AddSingleton<IDeviceManager, DeviceManager>();
  509. serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  510. serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  511. serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
  512. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  513. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  514. serviceCollection.AddSingleton<IDtoService, DtoService>();
  515. serviceCollection.AddSingleton<IChannelManager, ChannelManager>();
  516. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  517. serviceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  518. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  519. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  520. serviceCollection.AddSingleton<ISyncplayManager, SyncplayManager>();
  521. serviceCollection.AddSingleton<LiveTvDtoService>();
  522. serviceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  523. serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  524. serviceCollection.AddSingleton<INotificationManager, NotificationManager>();
  525. serviceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  526. serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
  527. serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  528. serviceCollection.AddSingleton<IActivityRepository, ActivityRepository>();
  529. serviceCollection.AddSingleton<IActivityManager, ActivityManager>();
  530. serviceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  531. serviceCollection.AddSingleton<ISessionContext, SessionContext>();
  532. serviceCollection.AddSingleton<IAuthService, AuthService>();
  533. serviceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  534. serviceCollection.AddSingleton<IResourceFileManager, ResourceFileManager>();
  535. serviceCollection.AddSingleton<EncodingHelper>();
  536. serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  537. }
  538. /// <summary>
  539. /// Create services registered with the service container that need to be initialized at application startup.
  540. /// </summary>
  541. /// <returns>A task representing the service initialization operation.</returns>
  542. public async Task InitializeServices()
  543. {
  544. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  545. await localizationManager.LoadAll().ConfigureAwait(false);
  546. _mediaEncoder = Resolve<IMediaEncoder>();
  547. _sessionManager = Resolve<ISessionManager>();
  548. _httpServer = Resolve<IHttpServer>();
  549. _httpClient = Resolve<IHttpClient>();
  550. ((SqliteDisplayPreferencesRepository)Resolve<IDisplayPreferencesRepository>()).Initialize();
  551. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  552. ((SqliteUserRepository)Resolve<IUserRepository>()).Initialize();
  553. ((ActivityRepository)Resolve<IActivityRepository>()).Initialize();
  554. SetStaticProperties();
  555. var userManager = (UserManager)Resolve<IUserManager>();
  556. userManager.Initialize();
  557. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  558. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, userManager);
  559. FindParts();
  560. }
  561. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  562. {
  563. // Distinct these to prevent users from reporting problems that aren't actually problems
  564. var commandLineArgs = Environment
  565. .GetCommandLineArgs()
  566. .Distinct();
  567. // Get all relevant environment variables
  568. var allEnvVars = Environment.GetEnvironmentVariables();
  569. var relevantEnvVars = new Dictionary<object, object>();
  570. foreach (var key in allEnvVars.Keys)
  571. {
  572. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  573. {
  574. relevantEnvVars.Add(key, allEnvVars[key]);
  575. }
  576. }
  577. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  578. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  579. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  580. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  581. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  582. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  583. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  584. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  585. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  586. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  587. }
  588. private X509Certificate2 GetCertificate(CertificateInfo info)
  589. {
  590. var certificateLocation = info?.Path;
  591. if (string.IsNullOrWhiteSpace(certificateLocation))
  592. {
  593. return null;
  594. }
  595. try
  596. {
  597. if (!File.Exists(certificateLocation))
  598. {
  599. return null;
  600. }
  601. // Don't use an empty string password
  602. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  603. var localCert = new X509Certificate2(certificateLocation, password);
  604. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  605. if (!localCert.HasPrivateKey)
  606. {
  607. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  608. return null;
  609. }
  610. return localCert;
  611. }
  612. catch (Exception ex)
  613. {
  614. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  615. return null;
  616. }
  617. }
  618. /// <summary>
  619. /// Dirty hacks.
  620. /// </summary>
  621. private void SetStaticProperties()
  622. {
  623. // For now there's no real way to inject these properly
  624. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  625. BaseItem.ConfigurationManager = ServerConfigurationManager;
  626. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  627. BaseItem.ProviderManager = Resolve<IProviderManager>();
  628. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  629. BaseItem.ItemRepository = Resolve<IItemRepository>();
  630. User.UserManager = Resolve<IUserManager>();
  631. BaseItem.FileSystem = _fileSystemManager;
  632. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  633. BaseItem.ChannelManager = Resolve<IChannelManager>();
  634. Video.LiveTvManager = Resolve<ILiveTvManager>();
  635. Folder.UserViewManager = Resolve<IUserViewManager>();
  636. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  637. UserView.CollectionManager = Resolve<ICollectionManager>();
  638. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  639. CollectionFolder.XmlSerializer = _xmlSerializer;
  640. CollectionFolder.JsonSerializer = Resolve<IJsonSerializer>();
  641. CollectionFolder.ApplicationHost = this;
  642. AuthenticatedAttribute.AuthService = Resolve<IAuthService>();
  643. }
  644. /// <summary>
  645. /// Finds plugin components and register them with the appropriate services.
  646. /// </summary>
  647. private void FindParts()
  648. {
  649. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  650. {
  651. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  652. ConfigurationManager.SaveConfiguration();
  653. }
  654. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  655. _plugins = GetExports<IPlugin>()
  656. .Select(LoadPlugin)
  657. .Where(i => i != null)
  658. .ToArray();
  659. _httpServer.Init(GetExportTypes<IService>(), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  660. Resolve<ILibraryManager>().AddParts(
  661. GetExports<IResolverIgnoreRule>(),
  662. GetExports<IItemResolver>(),
  663. GetExports<IIntroProvider>(),
  664. GetExports<IBaseItemComparer>(),
  665. GetExports<ILibraryPostScanTask>());
  666. Resolve<IProviderManager>().AddParts(
  667. GetExports<IImageProvider>(),
  668. GetExports<IMetadataService>(),
  669. GetExports<IMetadataProvider>(),
  670. GetExports<IMetadataSaver>(),
  671. GetExports<IExternalId>());
  672. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  673. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  674. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  675. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  676. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  677. Resolve<IUserManager>().AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  678. Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>());
  679. }
  680. private IPlugin LoadPlugin(IPlugin plugin)
  681. {
  682. try
  683. {
  684. if (plugin is IPluginAssembly assemblyPlugin)
  685. {
  686. var assembly = plugin.GetType().Assembly;
  687. var assemblyName = assembly.GetName();
  688. var assemblyFilePath = assembly.Location;
  689. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  690. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  691. try
  692. {
  693. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  694. if (idAttributes.Length > 0)
  695. {
  696. var attribute = (GuidAttribute)idAttributes[0];
  697. var assemblyId = new Guid(attribute.Value);
  698. assemblyPlugin.SetId(assemblyId);
  699. }
  700. }
  701. catch (Exception ex)
  702. {
  703. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  704. }
  705. }
  706. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  707. {
  708. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  709. }
  710. }
  711. catch (Exception ex)
  712. {
  713. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  714. return null;
  715. }
  716. return plugin;
  717. }
  718. /// <summary>
  719. /// Discovers the types.
  720. /// </summary>
  721. protected void DiscoverTypes()
  722. {
  723. Logger.LogInformation("Loading assemblies");
  724. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  725. }
  726. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  727. {
  728. foreach (var ass in assemblies)
  729. {
  730. Type[] exportedTypes;
  731. try
  732. {
  733. exportedTypes = ass.GetExportedTypes();
  734. }
  735. catch (FileNotFoundException ex)
  736. {
  737. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  738. continue;
  739. }
  740. foreach (Type type in exportedTypes)
  741. {
  742. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  743. {
  744. yield return type;
  745. }
  746. }
  747. }
  748. }
  749. private CertificateInfo CertificateInfo { get; set; }
  750. public X509Certificate2 Certificate { get; private set; }
  751. private IEnumerable<string> GetUrlPrefixes()
  752. {
  753. var hosts = new[] { "+" };
  754. return hosts.SelectMany(i =>
  755. {
  756. var prefixes = new List<string>
  757. {
  758. "http://" + i + ":" + HttpPort + "/"
  759. };
  760. if (CertificateInfo != null)
  761. {
  762. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  763. }
  764. return prefixes;
  765. });
  766. }
  767. /// <summary>
  768. /// Called when [configuration updated].
  769. /// </summary>
  770. /// <param name="sender">The sender.</param>
  771. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  772. protected void OnConfigurationUpdated(object sender, EventArgs e)
  773. {
  774. var requiresRestart = false;
  775. // Don't do anything if these haven't been set yet
  776. if (HttpPort != 0 && HttpsPort != 0)
  777. {
  778. // Need to restart if ports have changed
  779. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  780. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  781. {
  782. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  783. {
  784. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  785. ServerConfigurationManager.SaveConfiguration();
  786. requiresRestart = true;
  787. }
  788. }
  789. }
  790. if (!_httpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  791. {
  792. requiresRestart = true;
  793. }
  794. var currentCertPath = CertificateInfo?.Path;
  795. var newCertPath = ServerConfigurationManager.Configuration.CertificatePath;
  796. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  797. {
  798. requiresRestart = true;
  799. }
  800. if (requiresRestart)
  801. {
  802. Logger.LogInformation("App needs to be restarted due to configuration change.");
  803. NotifyPendingRestart();
  804. }
  805. }
  806. /// <summary>
  807. /// Notifies that the kernel that a change has been made that requires a restart
  808. /// </summary>
  809. public void NotifyPendingRestart()
  810. {
  811. Logger.LogInformation("App needs to be restarted.");
  812. var changed = !HasPendingRestart;
  813. HasPendingRestart = true;
  814. if (changed)
  815. {
  816. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  817. }
  818. }
  819. /// <summary>
  820. /// Restarts this instance.
  821. /// </summary>
  822. public void Restart()
  823. {
  824. if (!CanSelfRestart)
  825. {
  826. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  827. }
  828. if (IsShuttingDown)
  829. {
  830. return;
  831. }
  832. IsShuttingDown = true;
  833. Task.Run(async () =>
  834. {
  835. try
  836. {
  837. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  838. }
  839. catch (Exception ex)
  840. {
  841. Logger.LogError(ex, "Error sending server restart notification");
  842. }
  843. Logger.LogInformation("Calling RestartInternal");
  844. RestartInternal();
  845. });
  846. }
  847. protected abstract void RestartInternal();
  848. /// <summary>
  849. /// Gets the composable part assemblies.
  850. /// </summary>
  851. /// <returns>IEnumerable{Assembly}.</returns>
  852. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  853. {
  854. if (Directory.Exists(ApplicationPaths.PluginsPath))
  855. {
  856. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  857. {
  858. Assembly plugAss;
  859. try
  860. {
  861. plugAss = Assembly.LoadFrom(file);
  862. }
  863. catch (FileLoadException ex)
  864. {
  865. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  866. continue;
  867. }
  868. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  869. yield return plugAss;
  870. }
  871. }
  872. // Include composable parts in the Api assembly
  873. yield return typeof(ApiEntryPoint).Assembly;
  874. // Include composable parts in the Dashboard assembly
  875. yield return typeof(DashboardService).Assembly;
  876. // Include composable parts in the Model assembly
  877. yield return typeof(SystemInfo).Assembly;
  878. // Include composable parts in the Common assembly
  879. yield return typeof(IApplicationHost).Assembly;
  880. // Include composable parts in the Controller assembly
  881. yield return typeof(IServerApplicationHost).Assembly;
  882. // Include composable parts in the Providers assembly
  883. yield return typeof(ProviderUtils).Assembly;
  884. // Include composable parts in the Photos assembly
  885. yield return typeof(PhotoProvider).Assembly;
  886. // Emby.Server implementations
  887. yield return typeof(InstallationManager).Assembly;
  888. // MediaEncoding
  889. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  890. // Dlna
  891. yield return typeof(DlnaEntryPoint).Assembly;
  892. // Local metadata
  893. yield return typeof(BoxSetXmlSaver).Assembly;
  894. // Notifications
  895. yield return typeof(NotificationManager).Assembly;
  896. // Xbmc
  897. yield return typeof(ArtistNfoProvider).Assembly;
  898. foreach (var i in GetAssembliesWithPartsInternal())
  899. {
  900. yield return i;
  901. }
  902. }
  903. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  904. /// <summary>
  905. /// Gets the system status.
  906. /// </summary>
  907. /// <param name="cancellationToken">The cancellation token.</param>
  908. /// <returns>SystemInfo.</returns>
  909. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  910. {
  911. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  912. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  913. return new SystemInfo
  914. {
  915. HasPendingRestart = HasPendingRestart,
  916. IsShuttingDown = IsShuttingDown,
  917. Version = ApplicationVersionString,
  918. WebSocketPortNumber = HttpPort,
  919. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  920. Id = SystemId,
  921. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  922. WebPath = ApplicationPaths.WebPath,
  923. LogPath = ApplicationPaths.LogDirectoryPath,
  924. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  925. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  926. CachePath = ApplicationPaths.CachePath,
  927. HttpServerPortNumber = HttpPort,
  928. SupportsHttps = SupportsHttps,
  929. HttpsPortNumber = HttpsPort,
  930. OperatingSystem = OperatingSystem.Id.ToString(),
  931. OperatingSystemDisplayName = OperatingSystem.Name,
  932. CanSelfRestart = CanSelfRestart,
  933. CanLaunchWebBrowser = CanLaunchWebBrowser,
  934. HasUpdateAvailable = HasUpdateAvailable,
  935. TranscodingTempPath = transcodingTempPath,
  936. ServerName = FriendlyName,
  937. LocalAddress = localAddress,
  938. SupportsLibraryMonitor = true,
  939. EncoderLocation = _mediaEncoder.EncoderLocation,
  940. SystemArchitecture = RuntimeInformation.OSArchitecture,
  941. PackageName = _startupOptions.PackageName
  942. };
  943. }
  944. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  945. => _networkManager.GetMacAddresses()
  946. .Select(i => new WakeOnLanInfo(i))
  947. .ToList();
  948. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  949. {
  950. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  951. return new PublicSystemInfo
  952. {
  953. Version = ApplicationVersionString,
  954. ProductName = ApplicationProductName,
  955. Id = SystemId,
  956. OperatingSystem = OperatingSystem.Id.ToString(),
  957. ServerName = FriendlyName,
  958. LocalAddress = localAddress
  959. };
  960. }
  961. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  962. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  963. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken, bool forceHttp = false)
  964. {
  965. try
  966. {
  967. // Return the first matched address, if found, or the first known local address
  968. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  969. foreach (var address in addresses)
  970. {
  971. return GetLocalApiUrl(address, forceHttp);
  972. }
  973. return null;
  974. }
  975. catch (Exception ex)
  976. {
  977. Logger.LogError(ex, "Error getting local Ip address information");
  978. }
  979. return null;
  980. }
  981. /// <summary>
  982. /// Removes the scope id from IPv6 addresses.
  983. /// </summary>
  984. /// <param name="address">The IPv6 address.</param>
  985. /// <returns>The IPv6 address without the scope id.</returns>
  986. private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
  987. {
  988. var index = address.IndexOf('%');
  989. if (index == -1)
  990. {
  991. return address;
  992. }
  993. return address.Slice(0, index);
  994. }
  995. /// <inheritdoc />
  996. public string GetLocalApiUrl(IPAddress ipAddress, bool forceHttp = false)
  997. {
  998. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  999. {
  1000. var str = RemoveScopeId(ipAddress.ToString());
  1001. Span<char> span = new char[str.Length + 2];
  1002. span[0] = '[';
  1003. str.CopyTo(span.Slice(1));
  1004. span[^1] = ']';
  1005. return GetLocalApiUrl(span, forceHttp);
  1006. }
  1007. return GetLocalApiUrl(ipAddress.ToString(), forceHttp);
  1008. }
  1009. /// <inheritdoc />
  1010. public string GetLocalApiUrl(ReadOnlySpan<char> host, bool forceHttp = false)
  1011. {
  1012. var url = new StringBuilder(64);
  1013. bool useHttps = EnableHttps && !forceHttp;
  1014. url.Append(useHttps ? "https://" : "http://")
  1015. .Append(host)
  1016. .Append(':')
  1017. .Append(useHttps ? HttpsPort : HttpPort);
  1018. string baseUrl = ServerConfigurationManager.Configuration.BaseUrl;
  1019. if (baseUrl.Length != 0)
  1020. {
  1021. url.Append(baseUrl);
  1022. }
  1023. return url.ToString();
  1024. }
  1025. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1026. {
  1027. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1028. }
  1029. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1030. {
  1031. var addresses = ServerConfigurationManager
  1032. .Configuration
  1033. .LocalNetworkAddresses
  1034. .Select(NormalizeConfiguredLocalAddress)
  1035. .Where(i => i != null)
  1036. .ToList();
  1037. if (addresses.Count == 0)
  1038. {
  1039. addresses.AddRange(_networkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1040. }
  1041. var resultList = new List<IPAddress>();
  1042. foreach (var address in addresses)
  1043. {
  1044. if (!allowLoopback)
  1045. {
  1046. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1047. {
  1048. continue;
  1049. }
  1050. }
  1051. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1052. if (valid)
  1053. {
  1054. resultList.Add(address);
  1055. if (limit > 0 && resultList.Count >= limit)
  1056. {
  1057. return resultList;
  1058. }
  1059. }
  1060. }
  1061. return resultList;
  1062. }
  1063. public IPAddress NormalizeConfiguredLocalAddress(string address)
  1064. {
  1065. var index = address.Trim('/').IndexOf('/');
  1066. if (index != -1)
  1067. {
  1068. address = address.Substring(index + 1);
  1069. }
  1070. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1071. {
  1072. return result;
  1073. }
  1074. return null;
  1075. }
  1076. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1077. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1078. {
  1079. if (address.Equals(IPAddress.Loopback)
  1080. || address.Equals(IPAddress.IPv6Loopback))
  1081. {
  1082. return true;
  1083. }
  1084. var apiUrl = GetLocalApiUrl(address);
  1085. apiUrl += "/system/ping";
  1086. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1087. {
  1088. return cachedResult;
  1089. }
  1090. try
  1091. {
  1092. using (var response = await _httpClient.SendAsync(
  1093. new HttpRequestOptions
  1094. {
  1095. Url = apiUrl,
  1096. LogErrorResponseBody = false,
  1097. BufferContent = false,
  1098. CancellationToken = cancellationToken
  1099. }, HttpMethod.Post).ConfigureAwait(false))
  1100. {
  1101. using (var reader = new StreamReader(response.Content))
  1102. {
  1103. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1104. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1105. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1106. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1107. return valid;
  1108. }
  1109. }
  1110. }
  1111. catch (OperationCanceledException)
  1112. {
  1113. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1114. throw;
  1115. }
  1116. catch (Exception ex)
  1117. {
  1118. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1119. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1120. return false;
  1121. }
  1122. }
  1123. public string FriendlyName =>
  1124. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1125. ? Environment.MachineName
  1126. : ServerConfigurationManager.Configuration.ServerName;
  1127. /// <summary>
  1128. /// Shuts down.
  1129. /// </summary>
  1130. public async Task Shutdown()
  1131. {
  1132. if (IsShuttingDown)
  1133. {
  1134. return;
  1135. }
  1136. IsShuttingDown = true;
  1137. try
  1138. {
  1139. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1140. }
  1141. catch (Exception ex)
  1142. {
  1143. Logger.LogError(ex, "Error sending server shutdown notification");
  1144. }
  1145. ShutdownInternal();
  1146. }
  1147. protected abstract void ShutdownInternal();
  1148. public event EventHandler HasUpdateAvailableChanged;
  1149. private bool _hasUpdateAvailable;
  1150. public bool HasUpdateAvailable
  1151. {
  1152. get => _hasUpdateAvailable;
  1153. set
  1154. {
  1155. var fireEvent = value && !_hasUpdateAvailable;
  1156. _hasUpdateAvailable = value;
  1157. if (fireEvent)
  1158. {
  1159. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1160. }
  1161. }
  1162. }
  1163. /// <summary>
  1164. /// Removes the plugin.
  1165. /// </summary>
  1166. /// <param name="plugin">The plugin.</param>
  1167. public void RemovePlugin(IPlugin plugin)
  1168. {
  1169. var list = _plugins.ToList();
  1170. list.Remove(plugin);
  1171. _plugins = list.ToArray();
  1172. }
  1173. public virtual void LaunchUrl(string url)
  1174. {
  1175. if (!CanLaunchWebBrowser)
  1176. {
  1177. throw new NotSupportedException();
  1178. }
  1179. var process = new Process
  1180. {
  1181. StartInfo = new ProcessStartInfo
  1182. {
  1183. FileName = url,
  1184. UseShellExecute = true,
  1185. ErrorDialog = false
  1186. },
  1187. EnableRaisingEvents = true
  1188. };
  1189. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1190. try
  1191. {
  1192. process.Start();
  1193. }
  1194. catch (Exception ex)
  1195. {
  1196. Logger.LogError(ex, "Error launching url: {url}", url);
  1197. throw;
  1198. }
  1199. }
  1200. public virtual void EnableLoopback(string appName)
  1201. {
  1202. }
  1203. private bool _disposed = false;
  1204. /// <summary>
  1205. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1206. /// </summary>
  1207. public void Dispose()
  1208. {
  1209. Dispose(true);
  1210. GC.SuppressFinalize(this);
  1211. }
  1212. /// <summary>
  1213. /// Releases unmanaged and - optionally - managed resources.
  1214. /// </summary>
  1215. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1216. protected virtual void Dispose(bool dispose)
  1217. {
  1218. if (_disposed)
  1219. {
  1220. return;
  1221. }
  1222. if (dispose)
  1223. {
  1224. var type = GetType();
  1225. Logger.LogInformation("Disposing {Type}", type.Name);
  1226. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1227. _disposableParts.Clear();
  1228. foreach (var part in parts)
  1229. {
  1230. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1231. try
  1232. {
  1233. part.Dispose();
  1234. }
  1235. catch (Exception ex)
  1236. {
  1237. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1238. }
  1239. }
  1240. }
  1241. _disposed = true;
  1242. }
  1243. }
  1244. internal class CertificateInfo
  1245. {
  1246. public string Path { get; set; }
  1247. public string Password { get; set; }
  1248. }
  1249. }