ApplicationHost.cs 48 KB

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