ApplicationHost.cs 68 KB

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