ApplicationHost.cs 69 KB

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