ApplicationHost.cs 70 KB

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