ApplicationHost.cs 71 KB

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