ApplicationHost.cs 49 KB

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