ApplicationHost.cs 50 KB

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