ApplicationHost.cs 68 KB

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