ApplicationHost.cs 48 KB

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