ApplicationHost.cs 47 KB

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