ApplicationHost.cs 71 KB

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