ApplicationHost.cs 69 KB

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