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