ApplicationHost.cs 48 KB

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