ApplicationHost.cs 70 KB

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