ApplicationHost.cs 71 KB

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