ApplicationHost.cs 68 KB

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