ApplicationHost.cs 50 KB

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