ApplicationHost.cs 69 KB

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