2
0

ApplicationHost.cs 69 KB

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