ApplicationHost.cs 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Reflection;
  10. using System.Runtime.InteropServices;
  11. using System.Security.Cryptography.X509Certificates;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using Emby.Dlna;
  16. using Emby.Dlna.Main;
  17. using Emby.Dlna.Ssdp;
  18. using Emby.Drawing;
  19. using Emby.Notifications;
  20. using Emby.Photos;
  21. using Emby.Server.Implementations.Activity;
  22. using Emby.Server.Implementations.Archiving;
  23. using Emby.Server.Implementations.Channels;
  24. using Emby.Server.Implementations.Collections;
  25. using Emby.Server.Implementations.Configuration;
  26. using Emby.Server.Implementations.Cryptography;
  27. using Emby.Server.Implementations.Data;
  28. using Emby.Server.Implementations.Devices;
  29. using Emby.Server.Implementations.Diagnostics;
  30. using Emby.Server.Implementations.Dto;
  31. using Emby.Server.Implementations.HttpServer;
  32. using Emby.Server.Implementations.HttpServer.Security;
  33. using Emby.Server.Implementations.IO;
  34. using Emby.Server.Implementations.Library;
  35. using Emby.Server.Implementations.LiveTv;
  36. using Emby.Server.Implementations.Localization;
  37. using Emby.Server.Implementations.Middleware;
  38. using Emby.Server.Implementations.Net;
  39. using Emby.Server.Implementations.Playlists;
  40. using Emby.Server.Implementations.Reflection;
  41. using Emby.Server.Implementations.ScheduledTasks;
  42. using Emby.Server.Implementations.Security;
  43. using Emby.Server.Implementations.Serialization;
  44. using Emby.Server.Implementations.Session;
  45. using Emby.Server.Implementations.SocketSharp;
  46. using Emby.Server.Implementations.TV;
  47. using Emby.Server.Implementations.Updates;
  48. using Emby.Server.Implementations.Xml;
  49. using MediaBrowser.Api;
  50. using MediaBrowser.Common;
  51. using MediaBrowser.Common.Configuration;
  52. using MediaBrowser.Common.Events;
  53. using MediaBrowser.Common.Extensions;
  54. using MediaBrowser.Common.Net;
  55. using MediaBrowser.Common.Plugins;
  56. using MediaBrowser.Common.Updates;
  57. using MediaBrowser.Controller;
  58. using MediaBrowser.Controller.Authentication;
  59. using MediaBrowser.Controller.Channels;
  60. using MediaBrowser.Controller.Chapters;
  61. using MediaBrowser.Controller.Collections;
  62. using MediaBrowser.Controller.Configuration;
  63. using MediaBrowser.Controller.Devices;
  64. using MediaBrowser.Controller.Dlna;
  65. using MediaBrowser.Controller.Drawing;
  66. using MediaBrowser.Controller.Dto;
  67. using MediaBrowser.Controller.Entities;
  68. using MediaBrowser.Controller.Library;
  69. using MediaBrowser.Controller.LiveTv;
  70. using MediaBrowser.Controller.MediaEncoding;
  71. using MediaBrowser.Controller.Net;
  72. using MediaBrowser.Controller.Notifications;
  73. using MediaBrowser.Controller.Persistence;
  74. using MediaBrowser.Controller.Playlists;
  75. using MediaBrowser.Controller.Plugins;
  76. using MediaBrowser.Controller.Providers;
  77. using MediaBrowser.Controller.Resolvers;
  78. using MediaBrowser.Controller.Security;
  79. using MediaBrowser.Controller.Session;
  80. using MediaBrowser.Controller.Sorting;
  81. using MediaBrowser.Controller.Subtitles;
  82. using MediaBrowser.Controller.TV;
  83. using MediaBrowser.LocalMetadata.Savers;
  84. using MediaBrowser.MediaEncoding.BdInfo;
  85. using MediaBrowser.Model.Activity;
  86. using MediaBrowser.Model.Configuration;
  87. using MediaBrowser.Model.Cryptography;
  88. using MediaBrowser.Model.Diagnostics;
  89. using MediaBrowser.Model.Dlna;
  90. using MediaBrowser.Model.Events;
  91. using MediaBrowser.Model.Extensions;
  92. using MediaBrowser.Model.Globalization;
  93. using MediaBrowser.Model.IO;
  94. using MediaBrowser.Model.MediaInfo;
  95. using MediaBrowser.Model.Net;
  96. using MediaBrowser.Model.Reflection;
  97. using MediaBrowser.Model.Serialization;
  98. using MediaBrowser.Model.Services;
  99. using MediaBrowser.Model.System;
  100. using MediaBrowser.Model.Tasks;
  101. using MediaBrowser.Model.Updates;
  102. using MediaBrowser.Model.Xml;
  103. using MediaBrowser.Providers.Chapters;
  104. using MediaBrowser.Providers.Manager;
  105. using MediaBrowser.Providers.Subtitles;
  106. using MediaBrowser.Providers.TV.TheTVDB;
  107. using MediaBrowser.WebDashboard.Api;
  108. using MediaBrowser.XbmcMetadata.Providers;
  109. using Microsoft.AspNetCore.Builder;
  110. using Microsoft.AspNetCore.Hosting;
  111. using Microsoft.AspNetCore.Http;
  112. using Microsoft.AspNetCore.Http.Extensions;
  113. using Microsoft.Extensions.Configuration;
  114. using Microsoft.Extensions.Logging;
  115. using Microsoft.Extensions.DependencyInjection;
  116. using Microsoft.Extensions.DependencyInjection.Extensions;
  117. using ServiceStack;
  118. namespace Emby.Server.Implementations
  119. {
  120. /// <summary>
  121. /// Class CompositionRoot
  122. /// </summary>
  123. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  124. {
  125. /// <summary>
  126. /// Gets a value indicating whether this instance can self restart.
  127. /// </summary>
  128. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  129. public abstract bool CanSelfRestart { get; }
  130. public virtual bool CanLaunchWebBrowser
  131. {
  132. get
  133. {
  134. if (!Environment.UserInteractive)
  135. {
  136. return false;
  137. }
  138. if (StartupOptions.IsService)
  139. {
  140. return false;
  141. }
  142. if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
  143. {
  144. return true;
  145. }
  146. if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
  147. {
  148. return true;
  149. }
  150. return false;
  151. }
  152. }
  153. /// <summary>
  154. /// Occurs when [has pending restart changed].
  155. /// </summary>
  156. public event EventHandler HasPendingRestartChanged;
  157. /// <summary>
  158. /// Occurs when [application updated].
  159. /// </summary>
  160. public event EventHandler<GenericEventArgs<PackageVersionInfo>> ApplicationUpdated;
  161. /// <summary>
  162. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  163. /// </summary>
  164. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  165. public bool HasPendingRestart { get; private set; }
  166. public bool IsShuttingDown { get; private set; }
  167. /// <summary>
  168. /// Gets or sets the logger.
  169. /// </summary>
  170. /// <value>The logger.</value>
  171. protected ILogger Logger { get; set; }
  172. /// <summary>
  173. /// Gets or sets the plugins.
  174. /// </summary>
  175. /// <value>The plugins.</value>
  176. public IPlugin[] Plugins { get; protected set; }
  177. /// <summary>
  178. /// Gets or sets the logger factory.
  179. /// </summary>
  180. /// <value>The logger factory.</value>
  181. public ILoggerFactory LoggerFactory { get; protected set; }
  182. /// <summary>
  183. /// Gets the application paths.
  184. /// </summary>
  185. /// <value>The application paths.</value>
  186. protected ServerApplicationPaths ApplicationPaths { get; set; }
  187. /// <summary>
  188. /// Gets all concrete types.
  189. /// </summary>
  190. /// <value>All concrete types.</value>
  191. public Type[] AllConcreteTypes { get; protected set; }
  192. /// <summary>
  193. /// The disposable parts
  194. /// </summary>
  195. protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
  196. /// <summary>
  197. /// Gets the configuration manager.
  198. /// </summary>
  199. /// <value>The configuration manager.</value>
  200. protected IConfigurationManager ConfigurationManager { get; set; }
  201. public IFileSystem FileSystemManager { get; set; }
  202. protected IEnvironmentInfo EnvironmentInfo { get; set; }
  203. public PackageVersionClass SystemUpdateLevel
  204. {
  205. get
  206. {
  207. #if BETA
  208. return PackageVersionClass.Beta;
  209. #endif
  210. return PackageVersionClass.Release;
  211. }
  212. }
  213. protected IServiceProvider _serviceProvider;
  214. /// <summary>
  215. /// Gets the server configuration manager.
  216. /// </summary>
  217. /// <value>The server configuration manager.</value>
  218. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  219. /// <summary>
  220. /// Gets the configuration manager.
  221. /// </summary>
  222. /// <returns>IConfigurationManager.</returns>
  223. protected IConfigurationManager GetConfigurationManager()
  224. {
  225. return new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager);
  226. }
  227. protected virtual IResourceFileManager CreateResourceFileManager()
  228. {
  229. return new ResourceFileManager(HttpResultFactory, LoggerFactory, FileSystemManager);
  230. }
  231. /// <summary>
  232. /// Gets or sets the user manager.
  233. /// </summary>
  234. /// <value>The user manager.</value>
  235. public IUserManager UserManager { get; set; }
  236. /// <summary>
  237. /// Gets or sets the library manager.
  238. /// </summary>
  239. /// <value>The library manager.</value>
  240. internal ILibraryManager LibraryManager { get; set; }
  241. /// <summary>
  242. /// Gets or sets the directory watchers.
  243. /// </summary>
  244. /// <value>The directory watchers.</value>
  245. private ILibraryMonitor LibraryMonitor { get; set; }
  246. /// <summary>
  247. /// Gets or sets the provider manager.
  248. /// </summary>
  249. /// <value>The provider manager.</value>
  250. private IProviderManager ProviderManager { get; set; }
  251. /// <summary>
  252. /// Gets or sets the HTTP server.
  253. /// </summary>
  254. /// <value>The HTTP server.</value>
  255. private IHttpServer HttpServer { get; set; }
  256. private IDtoService DtoService { get; set; }
  257. public IImageProcessor ImageProcessor { get; set; }
  258. /// <summary>
  259. /// Gets or sets the media encoder.
  260. /// </summary>
  261. /// <value>The media encoder.</value>
  262. private IMediaEncoder MediaEncoder { get; set; }
  263. private ISubtitleEncoder SubtitleEncoder { get; set; }
  264. private ISessionManager SessionManager { get; set; }
  265. private ILiveTvManager LiveTvManager { get; set; }
  266. public LocalizationManager LocalizationManager { get; set; }
  267. private IEncodingManager EncodingManager { get; set; }
  268. private IChannelManager ChannelManager { get; set; }
  269. /// <summary>
  270. /// Gets or sets the user data repository.
  271. /// </summary>
  272. /// <value>The user data repository.</value>
  273. private IUserDataManager UserDataManager { get; set; }
  274. private IUserRepository UserRepository { get; set; }
  275. internal SqliteItemRepository ItemRepository { get; set; }
  276. private INotificationManager NotificationManager { get; set; }
  277. private ISubtitleManager SubtitleManager { get; set; }
  278. private IChapterManager ChapterManager { get; set; }
  279. private IDeviceManager DeviceManager { get; set; }
  280. internal IUserViewManager UserViewManager { get; set; }
  281. private IAuthenticationRepository AuthenticationRepository { get; set; }
  282. private ITVSeriesManager TVSeriesManager { get; set; }
  283. private ICollectionManager CollectionManager { get; set; }
  284. private IMediaSourceManager MediaSourceManager { get; set; }
  285. private IPlaylistManager PlaylistManager { get; set; }
  286. private readonly IConfiguration _configuration;
  287. /// <summary>
  288. /// Gets or sets the installation manager.
  289. /// </summary>
  290. /// <value>The installation manager.</value>
  291. protected IInstallationManager InstallationManager { get; private set; }
  292. /// <summary>
  293. /// Gets or sets the zip client.
  294. /// </summary>
  295. /// <value>The zip client.</value>
  296. protected IZipClient ZipClient { get; private set; }
  297. protected IHttpResultFactory HttpResultFactory { get; private set; }
  298. protected IAuthService AuthService { get; private set; }
  299. public IStartupOptions StartupOptions { get; private set; }
  300. internal IImageEncoder ImageEncoder { get; private set; }
  301. protected IProcessFactory ProcessFactory { get; private set; }
  302. protected ICryptoProvider CryptographyProvider = new CryptographyProvider();
  303. protected readonly IXmlSerializer XmlSerializer;
  304. protected ISocketFactory SocketFactory { get; private set; }
  305. protected ITaskManager TaskManager { get; private set; }
  306. public IHttpClient HttpClient { get; private set; }
  307. protected INetworkManager NetworkManager { get; set; }
  308. public IJsonSerializer JsonSerializer { get; private set; }
  309. protected IIsoManager IsoManager { get; private set; }
  310. /// <summary>
  311. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  312. /// </summary>
  313. public ApplicationHost(ServerApplicationPaths applicationPaths,
  314. ILoggerFactory loggerFactory,
  315. IStartupOptions options,
  316. IFileSystem fileSystem,
  317. IEnvironmentInfo environmentInfo,
  318. IImageEncoder imageEncoder,
  319. INetworkManager networkManager,
  320. IConfiguration configuration)
  321. {
  322. _configuration = configuration;
  323. // hack alert, until common can target .net core
  324. BaseExtensions.CryptographyProvider = CryptographyProvider;
  325. XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory);
  326. NetworkManager = networkManager;
  327. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  328. EnvironmentInfo = environmentInfo;
  329. ApplicationPaths = applicationPaths;
  330. LoggerFactory = loggerFactory;
  331. FileSystemManager = fileSystem;
  332. ConfigurationManager = GetConfigurationManager();
  333. Logger = LoggerFactory.CreateLogger("App");
  334. StartupOptions = options;
  335. ImageEncoder = imageEncoder;
  336. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  337. NetworkManager.NetworkChanged += NetworkManager_NetworkChanged;
  338. }
  339. public string ExpandVirtualPath(string path)
  340. {
  341. var appPaths = ApplicationPaths;
  342. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  343. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  344. }
  345. public string ReverseVirtualPath(string path)
  346. {
  347. var appPaths = ApplicationPaths;
  348. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  349. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  350. }
  351. private string[] GetConfiguredLocalSubnets()
  352. {
  353. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  354. }
  355. private void NetworkManager_NetworkChanged(object sender, EventArgs e)
  356. {
  357. _validAddressResults.Clear();
  358. }
  359. public string ApplicationVersion => typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
  360. /// <summary>
  361. /// Gets the current application user agent
  362. /// </summary>
  363. /// <value>The application user agent.</value>
  364. public string ApplicationUserAgent => Name.Replace(' ','-') + "/" + ApplicationVersion;
  365. private string _productName;
  366. /// <summary>
  367. /// Gets the current application name
  368. /// </summary>
  369. /// <value>The application name.</value>
  370. public string ApplicationProductName => _productName ?? (_productName = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName);
  371. private DeviceId _deviceId;
  372. public string SystemId
  373. {
  374. get
  375. {
  376. if (_deviceId == null)
  377. {
  378. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  379. }
  380. return _deviceId.Value;
  381. }
  382. }
  383. /// <summary>
  384. /// Gets the name.
  385. /// </summary>
  386. /// <value>The name.</value>
  387. public string Name => ApplicationProductName;
  388. /// <summary>
  389. /// Creates an instance of type and resolves all constructor dependencies
  390. /// </summary>
  391. /// <param name="type">The type.</param>
  392. /// <returns>System.Object.</returns>
  393. public object CreateInstance(Type type)
  394. => ActivatorUtilities.CreateInstance(_serviceProvider, type);
  395. /// <summary>
  396. /// Creates an instance of type and resolves all constructor dependencies
  397. /// </summary>
  398. /// <param name="type">The type.</param>
  399. /// <returns>System.Object.</returns>
  400. public T CreateInstance<T>()
  401. => ActivatorUtilities.CreateInstance<T>(_serviceProvider);
  402. /// <summary>
  403. /// Creates the instance safe.
  404. /// </summary>
  405. /// <param name="typeInfo">The type information.</param>
  406. /// <returns>System.Object.</returns>
  407. protected object CreateInstanceSafe(Type type)
  408. {
  409. try
  410. {
  411. Logger.LogDebug("Creating instance of {Type}", type);
  412. return ActivatorUtilities.CreateInstance(_serviceProvider, type);
  413. }
  414. catch (Exception ex)
  415. {
  416. Logger.LogError(ex, "Error creating {Type}", type);
  417. return null;
  418. }
  419. }
  420. /// <summary>
  421. /// Resolves this instance.
  422. /// </summary>
  423. /// <typeparam name="T"></typeparam>
  424. /// <returns>``0.</returns>
  425. public T Resolve<T>() => _serviceProvider.GetService<T>();
  426. /// <summary>
  427. /// Gets the export types.
  428. /// </summary>
  429. /// <typeparam name="T"></typeparam>
  430. /// <returns>IEnumerable{Type}.</returns>
  431. public IEnumerable<Type> GetExportTypes<T>()
  432. {
  433. var currentType = typeof(T);
  434. return AllConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  435. }
  436. /// <summary>
  437. /// Gets the exports.
  438. /// </summary>
  439. /// <typeparam name="T"></typeparam>
  440. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  441. /// <returns>IEnumerable{``0}.</returns>
  442. public IEnumerable<T> GetExports<T>(bool manageLifetime = true)
  443. {
  444. var parts = GetExportTypes<T>()
  445. .Select(x => CreateInstanceSafe(x))
  446. .Where(i => i != null)
  447. .Cast<T>()
  448. .ToList(); // Convert to list so this isn't executed for each iteration
  449. if (manageLifetime)
  450. {
  451. lock (DisposableParts)
  452. {
  453. DisposableParts.AddRange(parts.OfType<IDisposable>());
  454. }
  455. }
  456. return parts;
  457. }
  458. /// <summary>
  459. /// Runs the startup tasks.
  460. /// </summary>
  461. public async Task RunStartupTasks()
  462. {
  463. Logger.LogInformation("Running startup tasks");
  464. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  465. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  466. MediaEncoder.SetFFmpegPath();
  467. //if (string.IsNullOrWhiteSpace(MediaEncoder.EncoderPath))
  468. //{
  469. // if (ServerConfigurationManager.Configuration.IsStartupWizardCompleted)
  470. // {
  471. // ServerConfigurationManager.Configuration.IsStartupWizardCompleted = false;
  472. // ServerConfigurationManager.SaveConfiguration();
  473. // }
  474. //}
  475. Logger.LogInformation("ServerId: {0}", SystemId);
  476. var entryPoints = GetExports<IServerEntryPoint>();
  477. var stopWatch = new Stopwatch();
  478. stopWatch.Start();
  479. await Task.WhenAll(StartEntryPoints(entryPoints, true));
  480. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  481. Logger.LogInformation("Core startup complete");
  482. HttpServer.GlobalResponse = null;
  483. stopWatch.Restart();
  484. await Task.WhenAll(StartEntryPoints(entryPoints, false));
  485. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  486. stopWatch.Stop();
  487. }
  488. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  489. {
  490. foreach (var entryPoint in entryPoints)
  491. {
  492. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  493. {
  494. continue;
  495. }
  496. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  497. yield return entryPoint.RunAsync();
  498. }
  499. }
  500. public async Task Init(IServiceCollection serviceCollection)
  501. {
  502. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  503. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  504. // Safeguard against invalid configuration
  505. if (HttpPort == HttpsPort)
  506. {
  507. HttpPort = ServerConfiguration.DefaultHttpPort;
  508. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  509. }
  510. JsonSerializer = new JsonSerializer(FileSystemManager);
  511. if (Plugins != null)
  512. {
  513. var pluginBuilder = new StringBuilder();
  514. foreach (var plugin in Plugins)
  515. {
  516. pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
  517. }
  518. Logger.LogInformation("Plugins: {plugins}", pluginBuilder.ToString());
  519. }
  520. DiscoverTypes();
  521. SetHttpLimit();
  522. await RegisterResources(serviceCollection);
  523. FindParts();
  524. string contentRoot = ServerConfigurationManager.Configuration.DashboardSourcePath;
  525. if (string.IsNullOrEmpty(contentRoot))
  526. {
  527. contentRoot = Path.Combine(ServerConfigurationManager.ApplicationPaths.ApplicationResourcesPath, "jellyfin-web", "src");
  528. }
  529. var host = new WebHostBuilder()
  530. .UseKestrel(options =>
  531. {
  532. options.ListenAnyIP(HttpPort);
  533. if (EnableHttps)
  534. {
  535. options.ListenAnyIP(HttpsPort, listenOptions => { listenOptions.UseHttps(Certificate); });
  536. }
  537. })
  538. .UseContentRoot(contentRoot)
  539. .ConfigureServices(services =>
  540. {
  541. services.AddResponseCompression();
  542. services.AddHttpContextAccessor();
  543. })
  544. .Configure(app =>
  545. {
  546. app.UseWebSockets();
  547. app.UseResponseCompression();
  548. // TODO app.UseMiddleware<WebSocketMiddleware>();
  549. app.Use(ExecuteWebsocketHandlerAsync);
  550. app.Use(ExecuteHttpHandlerAsync);
  551. })
  552. .Build();
  553. await host.StartAsync();
  554. }
  555. private async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func<Task> next)
  556. {
  557. if (!context.WebSockets.IsWebSocketRequest)
  558. {
  559. await next().ConfigureAwait(false);
  560. return;
  561. }
  562. await HttpServer.ProcessWebSocketRequest(context).ConfigureAwait(false);
  563. }
  564. private async Task ExecuteHttpHandlerAsync(HttpContext context, Func<Task> next)
  565. {
  566. if (context.WebSockets.IsWebSocketRequest)
  567. {
  568. await next().ConfigureAwait(false);
  569. return;
  570. }
  571. var request = context.Request;
  572. var response = context.Response;
  573. var localPath = context.Request.Path.ToString();
  574. var req = new WebSocketSharpRequest(request, response, request.Path, Logger);
  575. await HttpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, CancellationToken.None).ConfigureAwait(false);
  576. }
  577. protected virtual IHttpClient CreateHttpClient()
  578. {
  579. return new HttpClientManager.HttpClientManager(ApplicationPaths, LoggerFactory, FileSystemManager, () => ApplicationUserAgent);
  580. }
  581. public static IStreamHelper StreamHelper { get; set; }
  582. /// <summary>
  583. /// Registers resources that classes will depend on
  584. /// </summary>
  585. protected async Task RegisterResources(IServiceCollection serviceCollection)
  586. {
  587. serviceCollection.AddMemoryCache();
  588. serviceCollection.AddSingleton(ConfigurationManager);
  589. serviceCollection.AddSingleton<IApplicationHost>(this);
  590. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  591. serviceCollection.AddSingleton(JsonSerializer);
  592. serviceCollection.AddSingleton(LoggerFactory);
  593. serviceCollection.AddLogging();
  594. serviceCollection.AddSingleton(Logger);
  595. serviceCollection.AddSingleton(EnvironmentInfo);
  596. serviceCollection.AddSingleton(FileSystemManager);
  597. serviceCollection.AddSingleton<TvDbClientManager>();
  598. HttpClient = CreateHttpClient();
  599. serviceCollection.AddSingleton(HttpClient);
  600. serviceCollection.AddSingleton(NetworkManager);
  601. IsoManager = new IsoManager();
  602. serviceCollection.AddSingleton(IsoManager);
  603. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory, FileSystemManager);
  604. serviceCollection.AddSingleton(TaskManager);
  605. serviceCollection.AddSingleton(XmlSerializer);
  606. ProcessFactory = new ProcessFactory();
  607. serviceCollection.AddSingleton(ProcessFactory);
  608. ApplicationHost.StreamHelper = new StreamHelper();
  609. serviceCollection.AddSingleton(StreamHelper);
  610. serviceCollection.AddSingleton(CryptographyProvider);
  611. SocketFactory = new SocketFactory();
  612. serviceCollection.AddSingleton(SocketFactory);
  613. InstallationManager = new InstallationManager(LoggerFactory, this, ApplicationPaths, HttpClient, JsonSerializer, ServerConfigurationManager, FileSystemManager, CryptographyProvider, ZipClient, PackageRuntime);
  614. serviceCollection.AddSingleton(InstallationManager);
  615. ZipClient = new ZipClient();
  616. serviceCollection.AddSingleton(ZipClient);
  617. HttpResultFactory = new HttpResultFactory(LoggerFactory, FileSystemManager, JsonSerializer, StreamHelper);
  618. serviceCollection.AddSingleton(HttpResultFactory);
  619. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  620. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  621. serviceCollection.AddSingleton(ServerConfigurationManager);
  622. var assemblyInfo = new AssemblyInfo();
  623. serviceCollection.AddSingleton<IAssemblyInfo>(assemblyInfo);
  624. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LoggerFactory);
  625. await LocalizationManager.LoadAll();
  626. serviceCollection.AddSingleton<ILocalizationManager>(LocalizationManager);
  627. serviceCollection.AddSingleton<IBlurayExaminer>(new BdInfoExaminer(FileSystemManager));
  628. serviceCollection.AddSingleton<IXmlReaderSettingsFactory>(new XmlReaderSettingsFactory());
  629. UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
  630. serviceCollection.AddSingleton(UserDataManager);
  631. UserRepository = GetUserRepository();
  632. // This is only needed for disposal purposes. If removing this, make sure to have the manager handle disposing it
  633. serviceCollection.AddSingleton(UserRepository);
  634. var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory, JsonSerializer, ApplicationPaths, FileSystemManager);
  635. serviceCollection.AddSingleton<IDisplayPreferencesRepository>(displayPreferencesRepo);
  636. ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory, assemblyInfo);
  637. serviceCollection.AddSingleton<IItemRepository>(ItemRepository);
  638. AuthenticationRepository = GetAuthenticationRepository();
  639. serviceCollection.AddSingleton(AuthenticationRepository);
  640. UserManager = new UserManager(LoggerFactory, ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager);
  641. serviceCollection.AddSingleton(UserManager);
  642. LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
  643. serviceCollection.AddSingleton(LibraryManager);
  644. // TODO wtaylor: investigate use of second music manager
  645. var musicManager = new MusicManager(LibraryManager);
  646. serviceCollection.AddSingleton<IMusicManager>(new MusicManager(LibraryManager));
  647. LibraryMonitor = new LibraryMonitor(LoggerFactory, LibraryManager, ServerConfigurationManager, FileSystemManager, EnvironmentInfo);
  648. serviceCollection.AddSingleton(LibraryMonitor);
  649. serviceCollection.AddSingleton<ISearchEngine>(new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  650. CertificateInfo = GetCertificateInfo(true);
  651. Certificate = GetCertificate(CertificateInfo);
  652. HttpServer = new HttpListenerHost(this,
  653. LoggerFactory,
  654. ServerConfigurationManager,
  655. _configuration,
  656. NetworkManager,
  657. JsonSerializer,
  658. XmlSerializer,
  659. CreateHttpListener());
  660. HttpServer.GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
  661. serviceCollection.AddSingleton(HttpServer);
  662. ImageProcessor = GetImageProcessor();
  663. serviceCollection.AddSingleton(ImageProcessor);
  664. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  665. serviceCollection.AddSingleton(TVSeriesManager);
  666. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager);
  667. serviceCollection.AddSingleton(DeviceManager);
  668. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
  669. serviceCollection.AddSingleton(MediaSourceManager);
  670. SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
  671. serviceCollection.AddSingleton(SubtitleManager);
  672. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  673. serviceCollection.AddSingleton(ProviderManager);
  674. DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ProviderManager, this, () => MediaSourceManager, () => LiveTvManager);
  675. serviceCollection.AddSingleton(DtoService);
  676. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager);
  677. serviceCollection.AddSingleton(ChannelManager);
  678. SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager);
  679. serviceCollection.AddSingleton(SessionManager);
  680. serviceCollection.AddSingleton<IDlnaManager>(
  681. new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this));
  682. CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
  683. serviceCollection.AddSingleton(CollectionManager);
  684. PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory, UserManager, ProviderManager);
  685. serviceCollection.AddSingleton(PlaylistManager);
  686. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
  687. serviceCollection.AddSingleton(LiveTvManager);
  688. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  689. serviceCollection.AddSingleton(UserViewManager);
  690. NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager);
  691. serviceCollection.AddSingleton(NotificationManager);
  692. serviceCollection.AddSingleton<IDeviceDiscovery>(
  693. new DeviceDiscovery(LoggerFactory, ServerConfigurationManager, SocketFactory));
  694. ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository);
  695. serviceCollection.AddSingleton(ChapterManager);
  696. MediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  697. LoggerFactory,
  698. JsonSerializer,
  699. StartupOptions.FFmpegPath,
  700. StartupOptions.FFprobePath,
  701. ServerConfigurationManager,
  702. FileSystemManager,
  703. () => SubtitleEncoder,
  704. () => MediaSourceManager,
  705. ProcessFactory,
  706. 5000);
  707. serviceCollection.AddSingleton(MediaEncoder);
  708. EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager);
  709. serviceCollection.AddSingleton(EncodingManager);
  710. var activityLogRepo = GetActivityLogRepository();
  711. serviceCollection.AddSingleton(activityLogRepo);
  712. serviceCollection.AddSingleton<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager));
  713. var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
  714. serviceCollection.AddSingleton<IAuthorizationContext>(authContext);
  715. serviceCollection.AddSingleton<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  716. AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, SessionManager, NetworkManager);
  717. serviceCollection.AddSingleton(AuthService);
  718. SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory);
  719. serviceCollection.AddSingleton(SubtitleEncoder);
  720. serviceCollection.AddSingleton(CreateResourceFileManager());
  721. displayPreferencesRepo.Initialize();
  722. var userDataRepo = new SqliteUserDataRepository(LoggerFactory, ApplicationPaths);
  723. SetStaticProperties();
  724. ((UserManager)UserManager).Initialize();
  725. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  726. ItemRepository.Initialize(userDataRepo, UserManager);
  727. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  728. _serviceProvider = serviceCollection.BuildServiceProvider();
  729. }
  730. public virtual string PackageRuntime => "netcore";
  731. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, EnvironmentInfo.EnvironmentInfo environmentInfo)
  732. {
  733. // Distinct these to prevent users from reporting problems that aren't actually problems
  734. var commandLineArgs = Environment
  735. .GetCommandLineArgs()
  736. .Distinct();
  737. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  738. logger.LogInformation("Operating system: {OS} {OSVersion}", environmentInfo.OperatingSystemName, environmentInfo.OperatingSystemVersion);
  739. logger.LogInformation("Architecture: {Architecture}", environmentInfo.SystemArchitecture);
  740. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  741. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  742. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  743. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  744. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  745. }
  746. private void SetHttpLimit()
  747. {
  748. try
  749. {
  750. // Increase the max http request limit
  751. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  752. }
  753. catch (Exception ex)
  754. {
  755. Logger.LogError(ex, "Error setting http limit");
  756. }
  757. }
  758. private X509Certificate2 GetCertificate(CertificateInfo info)
  759. {
  760. var certificateLocation = info?.Path;
  761. if (string.IsNullOrWhiteSpace(certificateLocation))
  762. {
  763. return null;
  764. }
  765. try
  766. {
  767. if (!File.Exists(certificateLocation))
  768. {
  769. return null;
  770. }
  771. // Don't use an empty string password
  772. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  773. var localCert = new X509Certificate2(certificateLocation, password);
  774. //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  775. if (!localCert.HasPrivateKey)
  776. {
  777. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  778. return null;
  779. }
  780. return localCert;
  781. }
  782. catch (Exception ex)
  783. {
  784. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  785. return null;
  786. }
  787. }
  788. private IImageProcessor GetImageProcessor()
  789. {
  790. return new ImageProcessor(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
  791. }
  792. /// <summary>
  793. /// Gets the user repository.
  794. /// </summary>
  795. /// <returns>Task{IUserRepository}.</returns>
  796. private IUserRepository GetUserRepository()
  797. {
  798. var repo = new SqliteUserRepository(LoggerFactory, ApplicationPaths, JsonSerializer);
  799. repo.Initialize();
  800. return repo;
  801. }
  802. private IAuthenticationRepository GetAuthenticationRepository()
  803. {
  804. var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager);
  805. repo.Initialize();
  806. return repo;
  807. }
  808. private IActivityRepository GetActivityLogRepository()
  809. {
  810. var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager);
  811. repo.Initialize();
  812. return repo;
  813. }
  814. /// <summary>
  815. /// Dirty hacks
  816. /// </summary>
  817. private void SetStaticProperties()
  818. {
  819. ItemRepository.ImageProcessor = ImageProcessor;
  820. // For now there's no real way to inject these properly
  821. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  822. BaseItem.ConfigurationManager = ServerConfigurationManager;
  823. BaseItem.LibraryManager = LibraryManager;
  824. BaseItem.ProviderManager = ProviderManager;
  825. BaseItem.LocalizationManager = LocalizationManager;
  826. BaseItem.ItemRepository = ItemRepository;
  827. User.UserManager = UserManager;
  828. BaseItem.FileSystem = FileSystemManager;
  829. BaseItem.UserDataManager = UserDataManager;
  830. BaseItem.ChannelManager = ChannelManager;
  831. Video.LiveTvManager = LiveTvManager;
  832. Folder.UserViewManager = UserViewManager;
  833. UserView.TVSeriesManager = TVSeriesManager;
  834. UserView.PlaylistManager = PlaylistManager;
  835. UserView.CollectionManager = CollectionManager;
  836. BaseItem.MediaSourceManager = MediaSourceManager;
  837. CollectionFolder.XmlSerializer = XmlSerializer;
  838. CollectionFolder.JsonSerializer = JsonSerializer;
  839. CollectionFolder.ApplicationHost = this;
  840. AuthenticatedAttribute.AuthService = AuthService;
  841. }
  842. /// <summary>
  843. /// Finds the parts.
  844. /// </summary>
  845. protected void FindParts()
  846. {
  847. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  848. {
  849. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  850. ConfigurationManager.SaveConfiguration();
  851. }
  852. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  853. Plugins = GetExports<IPlugin>()
  854. .Select(LoadPlugin)
  855. .Where(i => i != null)
  856. .ToArray();
  857. HttpServer.Init(GetExports<IService>(false), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  858. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  859. GetExports<IItemResolver>(),
  860. GetExports<IIntroProvider>(),
  861. GetExports<IBaseItemComparer>(),
  862. GetExports<ILibraryPostScanTask>());
  863. ProviderManager.AddParts(GetExports<IImageProvider>(),
  864. GetExports<IMetadataService>(),
  865. GetExports<IMetadataProvider>(),
  866. GetExports<IMetadataSaver>(),
  867. GetExports<IExternalId>());
  868. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  869. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  870. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  871. ChannelManager.AddParts(GetExports<IChannel>());
  872. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  873. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  874. UserManager.AddParts(GetExports<IAuthenticationProvider>());
  875. IsoManager.AddParts(GetExports<IIsoMounter>());
  876. }
  877. private IPlugin LoadPlugin(IPlugin plugin)
  878. {
  879. try
  880. {
  881. if (plugin is IPluginAssembly assemblyPlugin)
  882. {
  883. var assembly = plugin.GetType().Assembly;
  884. var assemblyName = assembly.GetName();
  885. var assemblyFilePath = assembly.Location;
  886. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  887. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  888. try
  889. {
  890. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  891. if (idAttributes.Length > 0)
  892. {
  893. var attribute = (GuidAttribute)idAttributes[0];
  894. var assemblyId = new Guid(attribute.Value);
  895. assemblyPlugin.SetId(assemblyId);
  896. }
  897. }
  898. catch (Exception ex)
  899. {
  900. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  901. }
  902. }
  903. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  904. {
  905. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  906. }
  907. }
  908. catch (Exception ex)
  909. {
  910. Logger.LogError(ex, "Error loading plugin {pluginName}", plugin.GetType().FullName);
  911. return null;
  912. }
  913. return plugin;
  914. }
  915. /// <summary>
  916. /// Discovers the types.
  917. /// </summary>
  918. protected void DiscoverTypes()
  919. {
  920. Logger.LogInformation("Loading assemblies");
  921. AllConcreteTypes = GetComposablePartAssemblies()
  922. .SelectMany(x => x.ExportedTypes)
  923. .Where(type => type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  924. .ToArray();
  925. }
  926. private CertificateInfo CertificateInfo { get; set; }
  927. protected X509Certificate2 Certificate { get; private set; }
  928. private IEnumerable<string> GetUrlPrefixes()
  929. {
  930. var hosts = new[] { "+" };
  931. return hosts.SelectMany(i =>
  932. {
  933. var prefixes = new List<string>
  934. {
  935. "http://"+i+":" + HttpPort + "/"
  936. };
  937. if (CertificateInfo != null)
  938. {
  939. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  940. }
  941. return prefixes;
  942. });
  943. }
  944. protected IHttpListener CreateHttpListener() => new WebSocketSharpListener(Logger);
  945. private CertificateInfo GetCertificateInfo(bool generateCertificate)
  946. {
  947. if (!string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.CertificatePath))
  948. {
  949. // Custom cert
  950. return new CertificateInfo
  951. {
  952. Path = ServerConfigurationManager.Configuration.CertificatePath,
  953. Password = ServerConfigurationManager.Configuration.CertificatePassword
  954. };
  955. }
  956. // Generate self-signed cert
  957. var certHost = GetHostnameFromExternalDns(ServerConfigurationManager.Configuration.WanDdns);
  958. var certPath = Path.Combine(ServerConfigurationManager.ApplicationPaths.ProgramDataPath, "ssl", "cert_" + (certHost + "2").GetMD5().ToString("N") + ".pfx");
  959. var password = "embycert";
  960. //if (generateCertificate)
  961. //{
  962. // if (!File.Exists(certPath))
  963. // {
  964. // FileSystemManager.CreateDirectory(FileSystemManager.GetDirectoryName(certPath));
  965. // try
  966. // {
  967. // CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, password, Logger);
  968. // }
  969. // catch (Exception ex)
  970. // {
  971. // Logger.LogError(ex, "Error creating ssl cert");
  972. // return null;
  973. // }
  974. // }
  975. //}
  976. return new CertificateInfo
  977. {
  978. Path = certPath,
  979. Password = password
  980. };
  981. }
  982. /// <summary>
  983. /// Called when [configuration updated].
  984. /// </summary>
  985. /// <param name="sender">The sender.</param>
  986. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  987. protected void OnConfigurationUpdated(object sender, EventArgs e)
  988. {
  989. var requiresRestart = false;
  990. // Don't do anything if these haven't been set yet
  991. if (HttpPort != 0 && HttpsPort != 0)
  992. {
  993. // Need to restart if ports have changed
  994. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  995. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  996. {
  997. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  998. {
  999. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  1000. ServerConfigurationManager.SaveConfiguration();
  1001. requiresRestart = true;
  1002. }
  1003. }
  1004. }
  1005. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  1006. {
  1007. requiresRestart = true;
  1008. }
  1009. var currentCertPath = CertificateInfo == null ? null : CertificateInfo.Path;
  1010. var newCertInfo = GetCertificateInfo(false);
  1011. var newCertPath = newCertInfo == null ? null : newCertInfo.Path;
  1012. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  1013. {
  1014. requiresRestart = true;
  1015. }
  1016. if (requiresRestart)
  1017. {
  1018. Logger.LogInformation("App needs to be restarted due to configuration change.");
  1019. NotifyPendingRestart();
  1020. }
  1021. }
  1022. /// <summary>
  1023. /// Notifies that the kernel that a change has been made that requires a restart
  1024. /// </summary>
  1025. public void NotifyPendingRestart()
  1026. {
  1027. Logger.LogInformation("App needs to be restarted.");
  1028. var changed = !HasPendingRestart;
  1029. HasPendingRestart = true;
  1030. if (changed)
  1031. {
  1032. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  1033. }
  1034. }
  1035. /// <summary>
  1036. /// Restarts this instance.
  1037. /// </summary>
  1038. public void Restart()
  1039. {
  1040. if (!CanSelfRestart)
  1041. {
  1042. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  1043. }
  1044. if (IsShuttingDown)
  1045. {
  1046. return;
  1047. }
  1048. IsShuttingDown = true;
  1049. Task.Run(async () =>
  1050. {
  1051. try
  1052. {
  1053. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  1054. }
  1055. catch (Exception ex)
  1056. {
  1057. Logger.LogError(ex, "Error sending server restart notification");
  1058. }
  1059. Logger.LogInformation("Calling RestartInternal");
  1060. RestartInternal();
  1061. });
  1062. }
  1063. protected abstract void RestartInternal();
  1064. /// <summary>
  1065. /// Gets the composable part assemblies.
  1066. /// </summary>
  1067. /// <returns>IEnumerable{Assembly}.</returns>
  1068. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  1069. {
  1070. if (Directory.Exists(ApplicationPaths.PluginsPath))
  1071. {
  1072. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly))
  1073. {
  1074. Logger.LogInformation("Loading assembly {Path}", file);
  1075. yield return Assembly.LoadFrom(file);
  1076. }
  1077. }
  1078. // Include composable parts in the Api assembly
  1079. yield return typeof(ApiEntryPoint).Assembly;
  1080. // Include composable parts in the Dashboard assembly
  1081. yield return typeof(DashboardService).Assembly;
  1082. // Include composable parts in the Model assembly
  1083. yield return typeof(SystemInfo).Assembly;
  1084. // Include composable parts in the Common assembly
  1085. yield return typeof(IApplicationHost).Assembly;
  1086. // Include composable parts in the Controller assembly
  1087. yield return typeof(IServerApplicationHost).Assembly;
  1088. // Include composable parts in the Providers assembly
  1089. yield return typeof(ProviderUtils).Assembly;
  1090. // Include composable parts in the Photos assembly
  1091. yield return typeof(PhotoProvider).Assembly;
  1092. // Emby.Server implementations
  1093. yield return typeof(InstallationManager).Assembly;
  1094. // MediaEncoding
  1095. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  1096. // Dlna
  1097. yield return typeof(DlnaEntryPoint).Assembly;
  1098. // Local metadata
  1099. yield return typeof(BoxSetXmlSaver).Assembly;
  1100. // Notifications
  1101. yield return typeof(NotificationManager).Assembly;
  1102. // Xbmc
  1103. yield return typeof(ArtistNfoProvider).Assembly;
  1104. foreach (var i in GetAssembliesWithPartsInternal())
  1105. {
  1106. yield return i;
  1107. }
  1108. }
  1109. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  1110. /// <summary>
  1111. /// Gets the system status.
  1112. /// </summary>
  1113. /// <returns>SystemInfo.</returns>
  1114. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  1115. {
  1116. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1117. var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false);
  1118. return new SystemInfo
  1119. {
  1120. HasPendingRestart = HasPendingRestart,
  1121. IsShuttingDown = IsShuttingDown,
  1122. Version = ApplicationVersion,
  1123. ProductName = ApplicationProductName,
  1124. WebSocketPortNumber = HttpPort,
  1125. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  1126. Id = SystemId,
  1127. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1128. LogPath = ApplicationPaths.LogDirectoryPath,
  1129. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1130. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1131. CachePath = ApplicationPaths.CachePath,
  1132. HttpServerPortNumber = HttpPort,
  1133. SupportsHttps = SupportsHttps,
  1134. HttpsPortNumber = HttpsPort,
  1135. OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(),
  1136. OperatingSystemDisplayName = EnvironmentInfo.OperatingSystemName,
  1137. CanSelfRestart = CanSelfRestart,
  1138. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1139. WanAddress = wanAddress,
  1140. HasUpdateAvailable = HasUpdateAvailable,
  1141. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  1142. ServerName = FriendlyName,
  1143. LocalAddress = localAddress,
  1144. SupportsLibraryMonitor = true,
  1145. EncoderLocation = MediaEncoder.EncoderLocation,
  1146. SystemArchitecture = EnvironmentInfo.SystemArchitecture,
  1147. SystemUpdateLevel = SystemUpdateLevel,
  1148. PackageName = StartupOptions.PackageName
  1149. };
  1150. }
  1151. public WakeOnLanInfo[] GetWakeOnLanInfo()
  1152. {
  1153. return NetworkManager.GetMacAddresses()
  1154. .Select(i => new WakeOnLanInfo
  1155. {
  1156. MacAddress = i
  1157. })
  1158. .ToArray();
  1159. }
  1160. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1161. {
  1162. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1163. var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false);
  1164. return new PublicSystemInfo
  1165. {
  1166. Version = ApplicationVersion,
  1167. Id = SystemId,
  1168. OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(),
  1169. WanAddress = wanAddress,
  1170. ServerName = FriendlyName,
  1171. LocalAddress = localAddress
  1172. };
  1173. }
  1174. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1175. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1176. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1177. {
  1178. try
  1179. {
  1180. // Return the first matched address, if found, or the first known local address
  1181. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1182. foreach (var address in addresses)
  1183. {
  1184. return GetLocalApiUrl(address);
  1185. }
  1186. return null;
  1187. }
  1188. catch (Exception ex)
  1189. {
  1190. Logger.LogError(ex, "Error getting local Ip address information");
  1191. }
  1192. return null;
  1193. }
  1194. public async Task<string> GetWanApiUrl(CancellationToken cancellationToken)
  1195. {
  1196. const string url = "http://ipv4.icanhazip.com";
  1197. try
  1198. {
  1199. using (var response = await HttpClient.Get(new HttpRequestOptions
  1200. {
  1201. Url = url,
  1202. LogErrorResponseBody = false,
  1203. LogErrors = false,
  1204. LogRequest = false,
  1205. TimeoutMs = 10000,
  1206. BufferContent = false,
  1207. CancellationToken = cancellationToken
  1208. }))
  1209. {
  1210. return GetLocalApiUrl(response.ReadToEnd().Trim());
  1211. }
  1212. }
  1213. catch (Exception ex)
  1214. {
  1215. Logger.LogError(ex, "Error getting WAN Ip address information");
  1216. }
  1217. return null;
  1218. }
  1219. public string GetLocalApiUrl(IpAddressInfo ipAddress)
  1220. {
  1221. if (ipAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
  1222. {
  1223. return GetLocalApiUrl("[" + ipAddress.Address + "]");
  1224. }
  1225. return GetLocalApiUrl(ipAddress.Address);
  1226. }
  1227. public string GetLocalApiUrl(string host)
  1228. {
  1229. return string.Format("http://{0}:{1}",
  1230. host,
  1231. HttpPort.ToString(CultureInfo.InvariantCulture));
  1232. }
  1233. public Task<List<IpAddressInfo>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1234. {
  1235. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1236. }
  1237. private async Task<List<IpAddressInfo>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1238. {
  1239. var addresses = ServerConfigurationManager
  1240. .Configuration
  1241. .LocalNetworkAddresses
  1242. .Select(NormalizeConfiguredLocalAddress)
  1243. .Where(i => i != null)
  1244. .ToList();
  1245. if (addresses.Count == 0)
  1246. {
  1247. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1248. }
  1249. var resultList = new List<IpAddressInfo>();
  1250. foreach (var address in addresses)
  1251. {
  1252. if (!allowLoopback)
  1253. {
  1254. if (address.Equals(IpAddressInfo.Loopback) || address.Equals(IpAddressInfo.IPv6Loopback))
  1255. {
  1256. continue;
  1257. }
  1258. }
  1259. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1260. if (valid)
  1261. {
  1262. resultList.Add(address);
  1263. if (limit > 0 && resultList.Count >= limit)
  1264. {
  1265. return resultList;
  1266. }
  1267. }
  1268. }
  1269. return resultList;
  1270. }
  1271. private IpAddressInfo NormalizeConfiguredLocalAddress(string address)
  1272. {
  1273. var index = address.Trim('/').IndexOf('/');
  1274. if (index != -1)
  1275. {
  1276. address = address.Substring(index + 1);
  1277. }
  1278. if (NetworkManager.TryParseIpAddress(address.Trim('/'), out IpAddressInfo result))
  1279. {
  1280. return result;
  1281. }
  1282. return null;
  1283. }
  1284. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1285. private async Task<bool> IsIpAddressValidAsync(IpAddressInfo address, CancellationToken cancellationToken)
  1286. {
  1287. if (address.Equals(IpAddressInfo.Loopback) ||
  1288. address.Equals(IpAddressInfo.IPv6Loopback))
  1289. {
  1290. return true;
  1291. }
  1292. var apiUrl = GetLocalApiUrl(address);
  1293. apiUrl += "/system/ping";
  1294. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1295. {
  1296. return cachedResult;
  1297. }
  1298. var logPing = false;
  1299. #if DEBUG
  1300. logPing = true;
  1301. #endif
  1302. try
  1303. {
  1304. using (var response = await HttpClient.SendAsync(new HttpRequestOptions
  1305. {
  1306. Url = apiUrl,
  1307. LogErrorResponseBody = false,
  1308. LogErrors = logPing,
  1309. LogRequest = logPing,
  1310. TimeoutMs = 5000,
  1311. BufferContent = false,
  1312. CancellationToken = cancellationToken
  1313. }, "POST").ConfigureAwait(false))
  1314. {
  1315. using (var reader = new StreamReader(response.Content))
  1316. {
  1317. var result = reader.ReadToEnd();
  1318. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1319. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1320. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1321. return valid;
  1322. }
  1323. }
  1324. }
  1325. catch (OperationCanceledException)
  1326. {
  1327. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1328. throw;
  1329. }
  1330. catch (Exception ex)
  1331. {
  1332. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1333. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1334. return false;
  1335. }
  1336. }
  1337. public string FriendlyName =>
  1338. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1339. ? Environment.MachineName
  1340. : ServerConfigurationManager.Configuration.ServerName;
  1341. public int HttpPort { get; private set; }
  1342. public int HttpsPort { get; private set; }
  1343. /// <summary>
  1344. /// Shuts down.
  1345. /// </summary>
  1346. public async Task Shutdown()
  1347. {
  1348. if (IsShuttingDown)
  1349. {
  1350. return;
  1351. }
  1352. IsShuttingDown = true;
  1353. try
  1354. {
  1355. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1356. }
  1357. catch (Exception ex)
  1358. {
  1359. Logger.LogError(ex, "Error sending server shutdown notification");
  1360. }
  1361. ShutdownInternal();
  1362. }
  1363. protected abstract void ShutdownInternal();
  1364. public event EventHandler HasUpdateAvailableChanged;
  1365. private bool _hasUpdateAvailable;
  1366. public bool HasUpdateAvailable
  1367. {
  1368. get => _hasUpdateAvailable;
  1369. set
  1370. {
  1371. var fireEvent = value && !_hasUpdateAvailable;
  1372. _hasUpdateAvailable = value;
  1373. if (fireEvent)
  1374. {
  1375. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1376. }
  1377. }
  1378. }
  1379. /// <summary>
  1380. /// Removes the plugin.
  1381. /// </summary>
  1382. /// <param name="plugin">The plugin.</param>
  1383. public void RemovePlugin(IPlugin plugin)
  1384. {
  1385. var list = Plugins.ToList();
  1386. list.Remove(plugin);
  1387. Plugins = list.ToArray();
  1388. }
  1389. /// <summary>
  1390. /// This returns localhost in the case of no external dns, and the hostname if the
  1391. /// dns is prefixed with a valid Uri prefix.
  1392. /// </summary>
  1393. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  1394. /// <returns>The hostname in <paramref name="externalDns"/></returns>
  1395. private static string GetHostnameFromExternalDns(string externalDns)
  1396. {
  1397. if (string.IsNullOrEmpty(externalDns))
  1398. {
  1399. return "localhost";
  1400. }
  1401. try
  1402. {
  1403. return new Uri(externalDns).Host;
  1404. }
  1405. catch
  1406. {
  1407. return externalDns;
  1408. }
  1409. }
  1410. public virtual void LaunchUrl(string url)
  1411. {
  1412. if (!CanLaunchWebBrowser)
  1413. {
  1414. throw new NotSupportedException();
  1415. }
  1416. var process = ProcessFactory.Create(new ProcessOptions
  1417. {
  1418. FileName = url,
  1419. //EnableRaisingEvents = true,
  1420. UseShellExecute = true,
  1421. ErrorDialog = false
  1422. });
  1423. process.Exited += ProcessExited;
  1424. try
  1425. {
  1426. process.Start();
  1427. }
  1428. catch (Exception ex)
  1429. {
  1430. Logger.LogError(ex, "Error launching url: {url}", url);
  1431. throw;
  1432. }
  1433. }
  1434. private static void ProcessExited(object sender, EventArgs e)
  1435. {
  1436. ((IProcess)sender).Dispose();
  1437. }
  1438. public virtual void EnableLoopback(string appName)
  1439. {
  1440. }
  1441. /// <summary>
  1442. /// Called when [application updated].
  1443. /// </summary>
  1444. /// <param name="package">The package.</param>
  1445. protected void OnApplicationUpdated(PackageVersionInfo package)
  1446. {
  1447. Logger.LogInformation("Application has been updated to version {0}", package.versionStr);
  1448. ApplicationUpdated?.Invoke(this, new GenericEventArgs<PackageVersionInfo>
  1449. {
  1450. Argument = package
  1451. });
  1452. NotifyPendingRestart();
  1453. }
  1454. private bool _disposed;
  1455. /// <summary>
  1456. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1457. /// </summary>
  1458. public void Dispose()
  1459. {
  1460. if (!_disposed)
  1461. {
  1462. _disposed = true;
  1463. Dispose(true);
  1464. }
  1465. }
  1466. /// <summary>
  1467. /// Releases unmanaged and - optionally - managed resources.
  1468. /// </summary>
  1469. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1470. protected virtual void Dispose(bool dispose)
  1471. {
  1472. if (dispose)
  1473. {
  1474. var type = GetType();
  1475. Logger.LogInformation("Disposing {Type}", type.Name);
  1476. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1477. DisposableParts.Clear();
  1478. foreach (var part in parts)
  1479. {
  1480. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1481. try
  1482. {
  1483. part.Dispose();
  1484. }
  1485. catch (Exception ex)
  1486. {
  1487. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1488. }
  1489. }
  1490. }
  1491. }
  1492. }
  1493. internal class CertificateInfo
  1494. {
  1495. public string Path { get; set; }
  1496. public string Password { get; set; }
  1497. }
  1498. }