ApplicationHost.cs 68 KB

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