ApplicationHost.cs 69 KB

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