ApplicationHost.cs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Reflection;
  10. using System.Runtime.InteropServices;
  11. using System.Security.Cryptography.X509Certificates;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using Emby.Dlna;
  15. using Emby.Dlna.Main;
  16. using Emby.Dlna.Ssdp;
  17. using Emby.Drawing;
  18. using Emby.Notifications;
  19. using Emby.Photos;
  20. using Emby.Server.Implementations.Archiving;
  21. using Emby.Server.Implementations.Channels;
  22. using Emby.Server.Implementations.Collections;
  23. using Emby.Server.Implementations.Configuration;
  24. using Emby.Server.Implementations.Cryptography;
  25. using Emby.Server.Implementations.Data;
  26. using Emby.Server.Implementations.Devices;
  27. using Emby.Server.Implementations.Dto;
  28. using Emby.Server.Implementations.HttpServer.Security;
  29. using Emby.Server.Implementations.IO;
  30. using Emby.Server.Implementations.Library;
  31. using Emby.Server.Implementations.LiveTv;
  32. using Emby.Server.Implementations.Localization;
  33. using Emby.Server.Implementations.Net;
  34. using Emby.Server.Implementations.Playlists;
  35. using Emby.Server.Implementations.Plugins;
  36. using Emby.Server.Implementations.QuickConnect;
  37. using Emby.Server.Implementations.ScheduledTasks;
  38. using Emby.Server.Implementations.Security;
  39. using Emby.Server.Implementations.Serialization;
  40. using Emby.Server.Implementations.Session;
  41. using Emby.Server.Implementations.SyncPlay;
  42. using Emby.Server.Implementations.TV;
  43. using Emby.Server.Implementations.Udp;
  44. using Emby.Server.Implementations.Updates;
  45. using Jellyfin.Api.Helpers;
  46. using Jellyfin.Networking.Configuration;
  47. using Jellyfin.Networking.Manager;
  48. using MediaBrowser.Common;
  49. using MediaBrowser.Common.Configuration;
  50. using MediaBrowser.Common.Events;
  51. using MediaBrowser.Common.Net;
  52. using MediaBrowser.Common.Plugins;
  53. using MediaBrowser.Common.Updates;
  54. using MediaBrowser.Controller;
  55. using MediaBrowser.Controller.Channels;
  56. using MediaBrowser.Controller.Chapters;
  57. using MediaBrowser.Controller.Collections;
  58. using MediaBrowser.Controller.Configuration;
  59. using MediaBrowser.Controller.Devices;
  60. using MediaBrowser.Controller.Dlna;
  61. using MediaBrowser.Controller.Drawing;
  62. using MediaBrowser.Controller.Dto;
  63. using MediaBrowser.Controller.Entities;
  64. using MediaBrowser.Controller.Library;
  65. using MediaBrowser.Controller.LiveTv;
  66. using MediaBrowser.Controller.MediaEncoding;
  67. using MediaBrowser.Controller.Net;
  68. using MediaBrowser.Controller.Notifications;
  69. using MediaBrowser.Controller.Persistence;
  70. using MediaBrowser.Controller.Playlists;
  71. using MediaBrowser.Controller.Plugins;
  72. using MediaBrowser.Controller.Providers;
  73. using MediaBrowser.Controller.QuickConnect;
  74. using MediaBrowser.Controller.Resolvers;
  75. using MediaBrowser.Controller.Security;
  76. using MediaBrowser.Controller.Session;
  77. using MediaBrowser.Controller.Sorting;
  78. using MediaBrowser.Controller.Subtitles;
  79. using MediaBrowser.Controller.SyncPlay;
  80. using MediaBrowser.Controller.TV;
  81. using MediaBrowser.LocalMetadata.Savers;
  82. using MediaBrowser.MediaEncoding.BdInfo;
  83. using MediaBrowser.Model.Cryptography;
  84. using MediaBrowser.Model.Dlna;
  85. using MediaBrowser.Model.Globalization;
  86. using MediaBrowser.Model.IO;
  87. using MediaBrowser.Model.MediaInfo;
  88. using MediaBrowser.Model.Net;
  89. using MediaBrowser.Model.Serialization;
  90. using MediaBrowser.Model.System;
  91. using MediaBrowser.Model.Tasks;
  92. using MediaBrowser.Providers.Chapters;
  93. using MediaBrowser.Providers.Manager;
  94. using MediaBrowser.Providers.Plugins.Tmdb;
  95. using MediaBrowser.Providers.Subtitles;
  96. using MediaBrowser.XbmcMetadata.Providers;
  97. using Microsoft.AspNetCore.Http;
  98. using Microsoft.AspNetCore.Mvc;
  99. using Microsoft.Extensions.Configuration;
  100. using Microsoft.Extensions.DependencyInjection;
  101. using Microsoft.Extensions.Logging;
  102. using Prometheus.DotNetRuntime;
  103. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  104. using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
  105. namespace Emby.Server.Implementations
  106. {
  107. /// <summary>
  108. /// Class CompositionRoot.
  109. /// </summary>
  110. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  111. {
  112. /// <summary>
  113. /// The environment variable prefixes to log at server startup.
  114. /// </summary>
  115. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  116. private readonly IFileSystem _fileSystemManager;
  117. private readonly IConfiguration _startupConfig;
  118. private readonly IXmlSerializer _xmlSerializer;
  119. private readonly IStartupOptions _startupOptions;
  120. private readonly IPluginManager _pluginManager;
  121. private List<Type> _creatingInstances;
  122. private IMediaEncoder _mediaEncoder;
  123. private ISessionManager _sessionManager;
  124. private string[] _urlPrefixes;
  125. /// <summary>
  126. /// Gets a value indicating whether this instance can self restart.
  127. /// </summary>
  128. public bool CanSelfRestart => _startupOptions.RestartPath != null;
  129. public bool CoreStartupHasCompleted { get; private set; }
  130. public virtual bool CanLaunchWebBrowser
  131. {
  132. get
  133. {
  134. if (!Environment.UserInteractive)
  135. {
  136. return false;
  137. }
  138. if (_startupOptions.IsService)
  139. {
  140. return false;
  141. }
  142. if (OperatingSystem.Id == OperatingSystemId.Windows
  143. || OperatingSystem.Id == OperatingSystemId.Darwin)
  144. {
  145. return true;
  146. }
  147. return false;
  148. }
  149. }
  150. /// <summary>
  151. /// Gets the <see cref="INetworkManager"/> singleton instance.
  152. /// </summary>
  153. public INetworkManager NetManager { get; internal set; }
  154. /// <summary>
  155. /// Occurs when [has pending restart changed].
  156. /// </summary>
  157. public event EventHandler HasPendingRestartChanged;
  158. /// <summary>
  159. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  160. /// </summary>
  161. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  162. public bool HasPendingRestart { get; private set; }
  163. /// <inheritdoc />
  164. public bool IsShuttingDown { get; private set; }
  165. /// <summary>
  166. /// Gets the logger.
  167. /// </summary>
  168. protected ILogger<ApplicationHost> Logger { get; }
  169. protected IServiceCollection ServiceCollection { get; }
  170. /// <summary>
  171. /// Gets the logger factory.
  172. /// </summary>
  173. protected ILoggerFactory LoggerFactory { get; }
  174. /// <summary>
  175. /// Gets or sets the application paths.
  176. /// </summary>
  177. /// <value>The application paths.</value>
  178. protected IServerApplicationPaths ApplicationPaths { get; set; }
  179. /// <summary>
  180. /// Gets or sets all concrete types.
  181. /// </summary>
  182. /// <value>All concrete types.</value>
  183. private Type[] _allConcreteTypes;
  184. /// <summary>
  185. /// The disposable parts.
  186. /// </summary>
  187. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  188. /// <summary>
  189. /// Gets or sets the configuration manager.
  190. /// </summary>
  191. /// <value>The configuration manager.</value>
  192. public ServerConfigurationManager ConfigurationManager { get; set; }
  193. /// <summary>
  194. /// Gets or sets the service provider.
  195. /// </summary>
  196. public IServiceProvider ServiceProvider { get; set; }
  197. /// <summary>
  198. /// Gets the http port for the webhost.
  199. /// </summary>
  200. public int HttpPort { get; private set; }
  201. /// <summary>
  202. /// Gets the https port for the webhost.
  203. /// </summary>
  204. public int HttpsPort { get; private set; }
  205. /// <summary>
  206. /// Gets the value of the PublishedServerUrl setting.
  207. /// </summary>
  208. public string PublishedServerUrl => _startupOptions.PublishedServerUrl ?? _startupConfig[UdpServer.AddressOverrideConfigKey];
  209. /// <summary>
  210. /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
  211. /// </summary>
  212. /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
  213. /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
  214. /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
  215. /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param>
  216. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  217. /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
  218. public ApplicationHost(
  219. IServerApplicationPaths applicationPaths,
  220. ILoggerFactory loggerFactory,
  221. IStartupOptions options,
  222. IConfiguration startupConfig,
  223. IFileSystem fileSystem,
  224. IServiceCollection serviceCollection)
  225. {
  226. ApplicationPaths = applicationPaths;
  227. LoggerFactory = loggerFactory;
  228. _startupOptions = options;
  229. _startupConfig = startupConfig;
  230. _fileSystemManager = fileSystem;
  231. ServiceCollection = serviceCollection;
  232. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  233. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  234. ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
  235. ApplicationVersionString = ApplicationVersion.ToString(3);
  236. ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  237. _xmlSerializer = new MyXmlSerializer();
  238. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
  239. _pluginManager = new PluginManager(
  240. LoggerFactory.CreateLogger<PluginManager>(),
  241. this,
  242. ConfigurationManager.Configuration,
  243. ApplicationPaths.PluginsPath,
  244. ApplicationVersion);
  245. }
  246. /// <summary>
  247. /// Temporary function to migration network settings out of system.xml and into network.xml.
  248. /// TODO: remove at the point when a fixed migration path has been decided upon.
  249. /// </summary>
  250. private void MigrateNetworkConfiguration()
  251. {
  252. string path = Path.Combine(ConfigurationManager.CommonApplicationPaths.ConfigurationDirectoryPath, "network.xml");
  253. if (!File.Exists(path))
  254. {
  255. var networkSettings = new NetworkConfiguration();
  256. ClassMigrationHelper.CopyProperties(ConfigurationManager.Configuration, networkSettings);
  257. _xmlSerializer.SerializeToFile(networkSettings, path);
  258. Logger.LogDebug("Successfully migrated network settings.");
  259. }
  260. }
  261. public string ExpandVirtualPath(string path)
  262. {
  263. var appPaths = ApplicationPaths;
  264. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  265. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  266. }
  267. public string ReverseVirtualPath(string path)
  268. {
  269. var appPaths = ApplicationPaths;
  270. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  271. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  272. }
  273. /// <inheritdoc />
  274. public Version ApplicationVersion { get; }
  275. /// <inheritdoc />
  276. public string ApplicationVersionString { get; }
  277. /// <summary>
  278. /// Gets the current application user agent.
  279. /// </summary>
  280. /// <value>The application user agent.</value>
  281. public string ApplicationUserAgent { get; }
  282. /// <summary>
  283. /// Gets the email address for use within a comment section of a user agent field.
  284. /// Presently used to provide contact information to MusicBrainz service.
  285. /// </summary>
  286. public string ApplicationUserAgentAddress => "team@jellyfin.org";
  287. /// <summary>
  288. /// Gets the current application name.
  289. /// </summary>
  290. /// <value>The application name.</value>
  291. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  292. private DeviceId _deviceId;
  293. public string SystemId
  294. {
  295. get
  296. {
  297. _deviceId ??= new DeviceId(ApplicationPaths, LoggerFactory);
  298. return _deviceId.Value;
  299. }
  300. }
  301. /// <inheritdoc/>
  302. public string Name => ApplicationProductName;
  303. /// <summary>
  304. /// Creates an instance of type and resolves all constructor dependencies.
  305. /// </summary>
  306. /// <param name="type">The type.</param>
  307. /// <returns>System.Object.</returns>
  308. public object CreateInstance(Type type)
  309. => ActivatorUtilities.CreateInstance(ServiceProvider, type);
  310. /// <summary>
  311. /// Creates an instance of type and resolves all constructor dependencies.
  312. /// </summary>
  313. /// <typeparam name="T">The type.</typeparam>
  314. /// <returns>T.</returns>
  315. public T CreateInstance<T>()
  316. => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
  317. /// <summary>
  318. /// Creates the instance safe.
  319. /// </summary>
  320. /// <param name="type">The type.</param>
  321. /// <returns>System.Object.</returns>
  322. protected object CreateInstanceSafe(Type type)
  323. {
  324. _creatingInstances ??= new List<Type>();
  325. if (_creatingInstances.IndexOf(type) != -1)
  326. {
  327. Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
  328. foreach (var entry in _creatingInstances)
  329. {
  330. Logger.LogError("Called from: {TypeName}", entry.FullName);
  331. }
  332. _pluginManager.FailPlugin(type.Assembly);
  333. throw new ExternalException("DI Loop detected.");
  334. }
  335. try
  336. {
  337. _creatingInstances.Add(type);
  338. Logger.LogDebug("Creating instance of {Type}", type);
  339. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  340. }
  341. catch (Exception ex)
  342. {
  343. Logger.LogError(ex, "Error creating {Type}", type);
  344. // If this is a plugin fail it.
  345. _pluginManager.FailPlugin(type.Assembly);
  346. return null;
  347. }
  348. finally
  349. {
  350. _creatingInstances.Remove(type);
  351. }
  352. }
  353. /// <summary>
  354. /// Resolves this instance.
  355. /// </summary>
  356. /// <typeparam name="T">The type.</typeparam>
  357. /// <returns>``0.</returns>
  358. public T Resolve<T>() => ServiceProvider.GetService<T>();
  359. /// <inheritdoc/>
  360. public IEnumerable<Type> GetExportTypes<T>()
  361. {
  362. var currentType = typeof(T);
  363. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  364. }
  365. /// <inheritdoc />
  366. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  367. {
  368. // Convert to list so this isn't executed for each iteration
  369. var parts = GetExportTypes<T>()
  370. .Select(CreateInstanceSafe)
  371. .Where(i => i != null)
  372. .Cast<T>()
  373. .ToList();
  374. if (manageLifetime)
  375. {
  376. lock (_disposableParts)
  377. {
  378. _disposableParts.AddRange(parts.OfType<IDisposable>());
  379. }
  380. }
  381. return parts;
  382. }
  383. /// <inheritdoc />
  384. public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
  385. {
  386. // Convert to list so this isn't executed for each iteration
  387. var parts = GetExportTypes<T>()
  388. .Select(i => defaultFunc(i))
  389. .Where(i => i != null)
  390. .Cast<T>()
  391. .ToList();
  392. if (manageLifetime)
  393. {
  394. lock (_disposableParts)
  395. {
  396. _disposableParts.AddRange(parts.OfType<IDisposable>());
  397. }
  398. }
  399. return parts;
  400. }
  401. /// <summary>
  402. /// Runs the startup tasks.
  403. /// </summary>
  404. /// <returns><see cref="Task" />.</returns>
  405. public async Task RunStartupTasksAsync(CancellationToken cancellationToken)
  406. {
  407. cancellationToken.ThrowIfCancellationRequested();
  408. Logger.LogInformation("Running startup tasks");
  409. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  410. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  411. ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
  412. _mediaEncoder.SetFFmpegPath();
  413. Logger.LogInformation("ServerId: {0}", SystemId);
  414. var entryPoints = GetExports<IServerEntryPoint>();
  415. cancellationToken.ThrowIfCancellationRequested();
  416. var stopWatch = new Stopwatch();
  417. stopWatch.Start();
  418. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  419. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  420. Logger.LogInformation("Core startup complete");
  421. CoreStartupHasCompleted = true;
  422. cancellationToken.ThrowIfCancellationRequested();
  423. stopWatch.Restart();
  424. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  425. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  426. stopWatch.Stop();
  427. }
  428. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  429. {
  430. foreach (var entryPoint in entryPoints)
  431. {
  432. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  433. {
  434. continue;
  435. }
  436. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  437. yield return entryPoint.RunAsync();
  438. }
  439. }
  440. /// <inheritdoc/>
  441. public void Init()
  442. {
  443. DiscoverTypes();
  444. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  445. // Have to migrate settings here as migration subsystem not yet initialised.
  446. MigrateNetworkConfiguration();
  447. NetManager = new NetworkManager(ConfigurationManager, LoggerFactory.CreateLogger<NetworkManager>());
  448. // Initialize runtime stat collection
  449. if (ConfigurationManager.Configuration.EnableMetrics)
  450. {
  451. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  452. }
  453. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  454. HttpPort = networkConfiguration.HttpServerPortNumber;
  455. HttpsPort = networkConfiguration.HttpsPortNumber;
  456. // Safeguard against invalid configuration
  457. if (HttpPort == HttpsPort)
  458. {
  459. HttpPort = NetworkConfiguration.DefaultHttpPort;
  460. HttpsPort = NetworkConfiguration.DefaultHttpsPort;
  461. }
  462. CertificateInfo = new CertificateInfo
  463. {
  464. Path = networkConfiguration.CertificatePath,
  465. Password = networkConfiguration.CertificatePassword
  466. };
  467. Certificate = GetCertificate(CertificateInfo);
  468. RegisterServices();
  469. _pluginManager.RegisterServices(ServiceCollection);
  470. }
  471. /// <summary>
  472. /// Registers services/resources with the service collection that will be available via DI.
  473. /// </summary>
  474. protected virtual void RegisterServices()
  475. {
  476. ServiceCollection.AddSingleton(_startupOptions);
  477. ServiceCollection.AddMemoryCache();
  478. ServiceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
  479. ServiceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
  480. ServiceCollection.AddSingleton<IApplicationHost>(this);
  481. ServiceCollection.AddSingleton<IPluginManager>(_pluginManager);
  482. ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  483. ServiceCollection.AddSingleton(_fileSystemManager);
  484. ServiceCollection.AddSingleton<TmdbClientManager>();
  485. ServiceCollection.AddSingleton(NetManager);
  486. ServiceCollection.AddSingleton<ITaskManager, TaskManager>();
  487. ServiceCollection.AddSingleton(_xmlSerializer);
  488. ServiceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  489. ServiceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  490. ServiceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  491. ServiceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  492. ServiceCollection.AddSingleton<IZipClient, ZipClient>();
  493. ServiceCollection.AddSingleton<IServerApplicationHost>(this);
  494. ServiceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  495. ServiceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  496. ServiceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  497. ServiceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  498. ServiceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  499. ServiceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  500. ServiceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  501. ServiceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  502. ServiceCollection.AddSingleton<EncodingHelper>();
  503. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  504. ServiceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  505. ServiceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  506. ServiceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  507. ServiceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  508. ServiceCollection.AddSingleton<IMusicManager, MusicManager>();
  509. ServiceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  510. ServiceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  511. ServiceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  512. ServiceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  513. ServiceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  514. ServiceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  515. ServiceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  516. ServiceCollection.AddSingleton<IProviderManager, ProviderManager>();
  517. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  518. ServiceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  519. ServiceCollection.AddSingleton<IDtoService, DtoService>();
  520. ServiceCollection.AddSingleton<IChannelManager, ChannelManager>();
  521. ServiceCollection.AddSingleton<ISessionManager, SessionManager>();
  522. ServiceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  523. ServiceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  524. ServiceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  525. ServiceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  526. ServiceCollection.AddSingleton<LiveTvDtoService>();
  527. ServiceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  528. ServiceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  529. ServiceCollection.AddSingleton<INotificationManager, NotificationManager>();
  530. ServiceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  531. ServiceCollection.AddSingleton<IChapterManager, ChapterManager>();
  532. ServiceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  533. ServiceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  534. ServiceCollection.AddSingleton<ISessionContext, SessionContext>();
  535. ServiceCollection.AddSingleton<IAuthService, AuthService>();
  536. ServiceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  537. ServiceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  538. ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  539. ServiceCollection.AddSingleton<TranscodingJobHelper>();
  540. ServiceCollection.AddScoped<MediaInfoHelper>();
  541. ServiceCollection.AddScoped<AudioHelper>();
  542. ServiceCollection.AddScoped<DynamicHlsHelper>();
  543. ServiceCollection.AddSingleton<IDirectoryService, DirectoryService>();
  544. }
  545. /// <summary>
  546. /// Create services registered with the service container that need to be initialized at application startup.
  547. /// </summary>
  548. /// <returns>A task representing the service initialization operation.</returns>
  549. public async Task InitializeServices()
  550. {
  551. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  552. await localizationManager.LoadAll().ConfigureAwait(false);
  553. _mediaEncoder = Resolve<IMediaEncoder>();
  554. _sessionManager = Resolve<ISessionManager>();
  555. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  556. SetStaticProperties();
  557. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  558. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  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, X509KeyStorageFlags.UserKeySet);
  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 = ConfigurationManager;
  626. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  627. BaseItem.ProviderManager = Resolve<IProviderManager>();
  628. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  629. BaseItem.ItemRepository = Resolve<IItemRepository>();
  630. BaseItem.FileSystem = _fileSystemManager;
  631. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  632. BaseItem.ChannelManager = Resolve<IChannelManager>();
  633. Video.LiveTvManager = Resolve<ILiveTvManager>();
  634. Folder.UserViewManager = Resolve<IUserViewManager>();
  635. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  636. UserView.CollectionManager = Resolve<ICollectionManager>();
  637. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  638. CollectionFolder.XmlSerializer = _xmlSerializer;
  639. CollectionFolder.ApplicationHost = this;
  640. }
  641. /// <summary>
  642. /// Finds plugin components and register them with the appropriate services.
  643. /// </summary>
  644. private void FindParts()
  645. {
  646. if (!ConfigurationManager.Configuration.IsPortAuthorized)
  647. {
  648. ConfigurationManager.Configuration.IsPortAuthorized = true;
  649. ConfigurationManager.SaveConfiguration();
  650. }
  651. _pluginManager.CreatePlugins();
  652. _urlPrefixes = GetUrlPrefixes().ToArray();
  653. Resolve<ILibraryManager>().AddParts(
  654. GetExports<IResolverIgnoreRule>(),
  655. GetExports<IItemResolver>(),
  656. GetExports<IIntroProvider>(),
  657. GetExports<IBaseItemComparer>(),
  658. GetExports<ILibraryPostScanTask>());
  659. Resolve<IProviderManager>().AddParts(
  660. GetExports<IImageProvider>(),
  661. GetExports<IMetadataService>(),
  662. GetExports<IMetadataProvider>(),
  663. GetExports<IMetadataSaver>(),
  664. GetExports<IExternalId>());
  665. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  666. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  667. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  668. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  669. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  670. }
  671. /// <summary>
  672. /// Discovers the types.
  673. /// </summary>
  674. protected void DiscoverTypes()
  675. {
  676. Logger.LogInformation("Loading assemblies");
  677. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  678. }
  679. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  680. {
  681. foreach (var ass in assemblies)
  682. {
  683. Type[] exportedTypes;
  684. try
  685. {
  686. exportedTypes = ass.GetExportedTypes();
  687. }
  688. catch (FileNotFoundException ex)
  689. {
  690. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  691. _pluginManager.FailPlugin(ass);
  692. continue;
  693. }
  694. catch (TypeLoadException ex)
  695. {
  696. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  697. _pluginManager.FailPlugin(ass);
  698. continue;
  699. }
  700. foreach (Type type in exportedTypes)
  701. {
  702. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  703. {
  704. yield return type;
  705. }
  706. }
  707. }
  708. }
  709. private CertificateInfo CertificateInfo { get; set; }
  710. public X509Certificate2 Certificate { get; private set; }
  711. private IEnumerable<string> GetUrlPrefixes()
  712. {
  713. var hosts = new[] { "+" };
  714. return hosts.SelectMany(i =>
  715. {
  716. var prefixes = new List<string>
  717. {
  718. "http://" + i + ":" + HttpPort + "/"
  719. };
  720. if (CertificateInfo != null)
  721. {
  722. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  723. }
  724. return prefixes;
  725. });
  726. }
  727. /// <summary>
  728. /// Called when [configuration updated].
  729. /// </summary>
  730. /// <param name="sender">The sender.</param>
  731. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  732. protected void OnConfigurationUpdated(object sender, EventArgs e)
  733. {
  734. var requiresRestart = false;
  735. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  736. // Don't do anything if these haven't been set yet
  737. if (HttpPort != 0 && HttpsPort != 0)
  738. {
  739. // Need to restart if ports have changed
  740. if (networkConfiguration.HttpServerPortNumber != HttpPort ||
  741. networkConfiguration.HttpsPortNumber != HttpsPort)
  742. {
  743. if (ConfigurationManager.Configuration.IsPortAuthorized)
  744. {
  745. ConfigurationManager.Configuration.IsPortAuthorized = false;
  746. ConfigurationManager.SaveConfiguration();
  747. requiresRestart = true;
  748. }
  749. }
  750. }
  751. if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  752. {
  753. requiresRestart = true;
  754. }
  755. if (ValidateSslCertificate(networkConfiguration))
  756. {
  757. requiresRestart = true;
  758. }
  759. if (requiresRestart)
  760. {
  761. Logger.LogInformation("App needs to be restarted due to configuration change.");
  762. NotifyPendingRestart();
  763. }
  764. }
  765. /// <summary>
  766. /// Validates the SSL certificate.
  767. /// </summary>
  768. /// <param name="networkConfig">The new configuration.</param>
  769. /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
  770. private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
  771. {
  772. var newPath = networkConfig.CertificatePath;
  773. if (!string.IsNullOrWhiteSpace(newPath)
  774. && !string.Equals(CertificateInfo?.Path, newPath, StringComparison.Ordinal))
  775. {
  776. if (File.Exists(newPath))
  777. {
  778. return true;
  779. }
  780. throw new FileNotFoundException(
  781. string.Format(
  782. CultureInfo.InvariantCulture,
  783. "Certificate file '{0}' does not exist.",
  784. newPath));
  785. }
  786. return false;
  787. }
  788. /// <summary>
  789. /// Notifies that the kernel that a change has been made that requires a restart.
  790. /// </summary>
  791. public void NotifyPendingRestart()
  792. {
  793. Logger.LogInformation("App needs to be restarted.");
  794. var changed = !HasPendingRestart;
  795. HasPendingRestart = true;
  796. if (changed)
  797. {
  798. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  799. }
  800. }
  801. /// <summary>
  802. /// Restarts this instance.
  803. /// </summary>
  804. public void Restart()
  805. {
  806. if (!CanSelfRestart)
  807. {
  808. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  809. }
  810. if (IsShuttingDown)
  811. {
  812. return;
  813. }
  814. IsShuttingDown = true;
  815. Task.Run(async () =>
  816. {
  817. try
  818. {
  819. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  820. }
  821. catch (Exception ex)
  822. {
  823. Logger.LogError(ex, "Error sending server restart notification");
  824. }
  825. Logger.LogInformation("Calling RestartInternal");
  826. RestartInternal();
  827. });
  828. }
  829. protected abstract void RestartInternal();
  830. /// <summary>
  831. /// Gets the composable part assemblies.
  832. /// </summary>
  833. /// <returns>IEnumerable{Assembly}.</returns>
  834. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  835. {
  836. foreach (var p in _pluginManager.LoadAssemblies())
  837. {
  838. yield return p;
  839. }
  840. // Include composable parts in the Model assembly
  841. yield return typeof(SystemInfo).Assembly;
  842. // Include composable parts in the Common assembly
  843. yield return typeof(IApplicationHost).Assembly;
  844. // Include composable parts in the Controller assembly
  845. yield return typeof(IServerApplicationHost).Assembly;
  846. // Include composable parts in the Providers assembly
  847. yield return typeof(ProviderUtils).Assembly;
  848. // Include composable parts in the Photos assembly
  849. yield return typeof(PhotoProvider).Assembly;
  850. // Emby.Server implementations
  851. yield return typeof(InstallationManager).Assembly;
  852. // MediaEncoding
  853. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  854. // Dlna
  855. yield return typeof(DlnaEntryPoint).Assembly;
  856. // Local metadata
  857. yield return typeof(BoxSetXmlSaver).Assembly;
  858. // Notifications
  859. yield return typeof(NotificationManager).Assembly;
  860. // Xbmc
  861. yield return typeof(ArtistNfoProvider).Assembly;
  862. // Network
  863. yield return typeof(NetworkManager).Assembly;
  864. foreach (var i in GetAssembliesWithPartsInternal())
  865. {
  866. yield return i;
  867. }
  868. }
  869. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  870. /// <summary>
  871. /// Gets the system status.
  872. /// </summary>
  873. /// <param name="source">Where this request originated.</param>
  874. /// <returns>SystemInfo.</returns>
  875. public SystemInfo GetSystemInfo(IPAddress source)
  876. {
  877. return new SystemInfo
  878. {
  879. HasPendingRestart = HasPendingRestart,
  880. IsShuttingDown = IsShuttingDown,
  881. Version = ApplicationVersionString,
  882. WebSocketPortNumber = HttpPort,
  883. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  884. Id = SystemId,
  885. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  886. WebPath = ApplicationPaths.WebPath,
  887. LogPath = ApplicationPaths.LogDirectoryPath,
  888. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  889. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  890. CachePath = ApplicationPaths.CachePath,
  891. OperatingSystem = OperatingSystem.Id.ToString(),
  892. OperatingSystemDisplayName = OperatingSystem.Name,
  893. CanSelfRestart = CanSelfRestart,
  894. CanLaunchWebBrowser = CanLaunchWebBrowser,
  895. HasUpdateAvailable = HasUpdateAvailable,
  896. TranscodingTempPath = ConfigurationManager.GetTranscodePath(),
  897. ServerName = FriendlyName,
  898. LocalAddress = GetSmartApiUrl(source),
  899. SupportsLibraryMonitor = true,
  900. EncoderLocation = _mediaEncoder.EncoderLocation,
  901. SystemArchitecture = RuntimeInformation.OSArchitecture,
  902. PackageName = _startupOptions.PackageName
  903. };
  904. }
  905. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  906. => NetManager.GetMacAddresses()
  907. .Select(i => new WakeOnLanInfo(i))
  908. .ToList();
  909. public PublicSystemInfo GetPublicSystemInfo(IPAddress source)
  910. {
  911. return new PublicSystemInfo
  912. {
  913. Version = ApplicationVersionString,
  914. ProductName = ApplicationProductName,
  915. Id = SystemId,
  916. OperatingSystem = OperatingSystem.Id.ToString(),
  917. ServerName = FriendlyName,
  918. LocalAddress = GetSmartApiUrl(source),
  919. StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
  920. };
  921. }
  922. /// <inheritdoc/>
  923. public bool ListenWithHttps => Certificate != null && ConfigurationManager.GetNetworkConfiguration().EnableHttps;
  924. /// <inheritdoc/>
  925. public string GetSmartApiUrl(IPAddress ipAddress, int? port = null)
  926. {
  927. // Published server ends with a /
  928. if (!string.IsNullOrEmpty(PublishedServerUrl))
  929. {
  930. // Published server ends with a '/', so we need to remove it.
  931. return PublishedServerUrl.Trim('/');
  932. }
  933. string smart = NetManager.GetBindInterface(ipAddress, out port);
  934. // If the smartAPI doesn't start with http then treat it as a host or ip.
  935. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  936. {
  937. return smart.Trim('/');
  938. }
  939. return GetLocalApiUrl(smart.Trim('/'), null, port);
  940. }
  941. /// <inheritdoc/>
  942. public string GetSmartApiUrl(HttpRequest request, int? port = null)
  943. {
  944. // Published server ends with a /
  945. if (!string.IsNullOrEmpty(PublishedServerUrl))
  946. {
  947. // Published server ends with a '/', so we need to remove it.
  948. return PublishedServerUrl.Trim('/');
  949. }
  950. string smart = NetManager.GetBindInterface(request, out port);
  951. // If the smartAPI doesn't start with http then treat it as a host or ip.
  952. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  953. {
  954. return smart.Trim('/');
  955. }
  956. return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port);
  957. }
  958. /// <inheritdoc/>
  959. public string GetSmartApiUrl(string hostname, int? port = null)
  960. {
  961. // Published server ends with a /
  962. if (!string.IsNullOrEmpty(PublishedServerUrl))
  963. {
  964. // Published server ends with a '/', so we need to remove it.
  965. return PublishedServerUrl.Trim('/');
  966. }
  967. string smart = NetManager.GetBindInterface(hostname, out port);
  968. // If the smartAPI doesn't start with http then treat it as a host or ip.
  969. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  970. {
  971. return smart.Trim('/');
  972. }
  973. return GetLocalApiUrl(smart.Trim('/'), null, port);
  974. }
  975. /// <inheritdoc/>
  976. public string GetLoopbackHttpApiUrl()
  977. {
  978. if (NetManager.IsIP6Enabled)
  979. {
  980. return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort);
  981. }
  982. return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
  983. }
  984. /// <inheritdoc/>
  985. public string GetLocalApiUrl(string host, string scheme = null, int? port = null)
  986. {
  987. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  988. // not. For consistency, always trim the trailing slash.
  989. return new UriBuilder
  990. {
  991. Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
  992. Host = host,
  993. Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
  994. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  995. }.ToString().TrimEnd('/');
  996. }
  997. public string FriendlyName =>
  998. string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName)
  999. ? Environment.MachineName
  1000. : ConfigurationManager.Configuration.ServerName;
  1001. /// <summary>
  1002. /// Shuts down.
  1003. /// </summary>
  1004. public async Task Shutdown()
  1005. {
  1006. if (IsShuttingDown)
  1007. {
  1008. return;
  1009. }
  1010. IsShuttingDown = true;
  1011. try
  1012. {
  1013. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1014. }
  1015. catch (Exception ex)
  1016. {
  1017. Logger.LogError(ex, "Error sending server shutdown notification");
  1018. }
  1019. ShutdownInternal();
  1020. }
  1021. protected abstract void ShutdownInternal();
  1022. public event EventHandler HasUpdateAvailableChanged;
  1023. private bool _hasUpdateAvailable;
  1024. public bool HasUpdateAvailable
  1025. {
  1026. get => _hasUpdateAvailable;
  1027. set
  1028. {
  1029. var fireEvent = value && !_hasUpdateAvailable;
  1030. _hasUpdateAvailable = value;
  1031. if (fireEvent)
  1032. {
  1033. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1034. }
  1035. }
  1036. }
  1037. public IEnumerable<Assembly> GetApiPluginAssemblies()
  1038. {
  1039. var assemblies = _allConcreteTypes
  1040. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  1041. .Select(i => i.Assembly)
  1042. .Distinct();
  1043. foreach (var assembly in assemblies)
  1044. {
  1045. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  1046. yield return assembly;
  1047. }
  1048. }
  1049. public virtual void LaunchUrl(string url)
  1050. {
  1051. if (!CanLaunchWebBrowser)
  1052. {
  1053. throw new NotSupportedException();
  1054. }
  1055. var process = new Process
  1056. {
  1057. StartInfo = new ProcessStartInfo
  1058. {
  1059. FileName = url,
  1060. UseShellExecute = true,
  1061. ErrorDialog = false
  1062. },
  1063. EnableRaisingEvents = true
  1064. };
  1065. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1066. try
  1067. {
  1068. process.Start();
  1069. }
  1070. catch (Exception ex)
  1071. {
  1072. Logger.LogError(ex, "Error launching url: {url}", url);
  1073. throw;
  1074. }
  1075. }
  1076. private bool _disposed = false;
  1077. /// <summary>
  1078. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1079. /// </summary>
  1080. public void Dispose()
  1081. {
  1082. Dispose(true);
  1083. GC.SuppressFinalize(this);
  1084. }
  1085. /// <summary>
  1086. /// Releases unmanaged and - optionally - managed resources.
  1087. /// </summary>
  1088. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1089. protected virtual void Dispose(bool dispose)
  1090. {
  1091. if (_disposed)
  1092. {
  1093. return;
  1094. }
  1095. if (dispose)
  1096. {
  1097. var type = GetType();
  1098. Logger.LogInformation("Disposing {Type}", type.Name);
  1099. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1100. _disposableParts.Clear();
  1101. foreach (var part in parts)
  1102. {
  1103. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1104. try
  1105. {
  1106. part.Dispose();
  1107. }
  1108. catch (Exception ex)
  1109. {
  1110. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1111. }
  1112. }
  1113. }
  1114. _disposed = true;
  1115. }
  1116. }
  1117. internal class CertificateInfo
  1118. {
  1119. public string Path { get; set; }
  1120. public string Password { get; set; }
  1121. }
  1122. }