ApplicationHost.cs 48 KB

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