ApplicationHost.cs 69 KB

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