ApplicationHost.cs 48 KB

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