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. // TODO certs
  534. options.Listen(IPAddress.Any, HttpsPort, listenOptions => { listenOptions.UseHttps(); });
  535. options.Listen(IPAddress.Loopback, HttpsPort, listenOptions => { listenOptions.UseHttps(); });
  536. })
  537. .UseContentRoot(Path.Combine(Directory.GetCurrentDirectory(), "jellyfin-web", "src"))
  538. .ConfigureServices(services =>
  539. {
  540. services.AddResponseCompression();
  541. services.AddHttpContextAccessor();
  542. services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
  543. })
  544. .Configure(app =>
  545. {
  546. app.UseWebSockets();
  547. app.UseResponseCompression();
  548. // TODO app.UseMiddleware<WebSocketMiddleware>();
  549. app.Use(ExecuteWebsocketHandlerAsync);
  550. app.Use(ExecuteHttpHandlerAsync);
  551. })
  552. .Build();
  553. }
  554. public async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func<Task> next)
  555. {
  556. if (!context.WebSockets.IsWebSocketRequest)
  557. {
  558. await next();
  559. return;
  560. }
  561. await HttpServer.ProcessWebSocketRequest(context).ConfigureAwait(false);
  562. }
  563. public async Task ExecuteHttpHandlerAsync(HttpContext context, Func<Task> next)
  564. {
  565. if (context.WebSockets.IsWebSocketRequest)
  566. {
  567. await next();
  568. return;
  569. }
  570. var request = context.Request;
  571. var response = context.Response;
  572. var localPath = context.Request.Path.ToString();
  573. var req = new WebSocketSharpRequest(request, response, request.Path, Logger);
  574. await HttpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, CancellationToken.None).ConfigureAwait(false);
  575. }
  576. protected virtual IHttpClient CreateHttpClient()
  577. {
  578. return new HttpClientManager.HttpClientManager(ApplicationPaths, LoggerFactory, FileSystemManager, () => ApplicationUserAgent);
  579. }
  580. public static IStreamHelper StreamHelper { get; set; }
  581. /// <summary>
  582. /// Registers resources that classes will depend on
  583. /// </summary>
  584. protected async Task RegisterResources(IServiceCollection serviceCollection)
  585. {
  586. serviceCollection.AddMemoryCache();
  587. serviceCollection.AddSingleton(ConfigurationManager);
  588. serviceCollection.AddSingleton<IApplicationHost>(this);
  589. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  590. serviceCollection.AddSingleton(JsonSerializer);
  591. serviceCollection.AddSingleton(LoggerFactory);
  592. serviceCollection.AddLogging();
  593. serviceCollection.AddSingleton(Logger);
  594. serviceCollection.AddSingleton(EnvironmentInfo);
  595. serviceCollection.AddSingleton(FileSystemManager);
  596. serviceCollection.AddSingleton<TvDbClientManager>();
  597. HttpClient = CreateHttpClient();
  598. serviceCollection.AddSingleton(HttpClient);
  599. serviceCollection.AddSingleton(NetworkManager);
  600. IsoManager = new IsoManager();
  601. serviceCollection.AddSingleton(IsoManager);
  602. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory, FileSystemManager);
  603. serviceCollection.AddSingleton(TaskManager);
  604. serviceCollection.AddSingleton(XmlSerializer);
  605. ProcessFactory = new ProcessFactory();
  606. serviceCollection.AddSingleton(ProcessFactory);
  607. ApplicationHost.StreamHelper = new StreamHelper();
  608. serviceCollection.AddSingleton(StreamHelper);
  609. serviceCollection.AddSingleton(CryptographyProvider);
  610. SocketFactory = new SocketFactory();
  611. serviceCollection.AddSingleton(SocketFactory);
  612. InstallationManager = new InstallationManager(LoggerFactory, this, ApplicationPaths, HttpClient, JsonSerializer, ServerConfigurationManager, FileSystemManager, CryptographyProvider, ZipClient, PackageRuntime);
  613. serviceCollection.AddSingleton(InstallationManager);
  614. ZipClient = new ZipClient();
  615. serviceCollection.AddSingleton(ZipClient);
  616. HttpResultFactory = new HttpResultFactory(LoggerFactory, FileSystemManager, JsonSerializer, CreateBrotliCompressor());
  617. serviceCollection.AddSingleton(HttpResultFactory);
  618. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  619. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  620. serviceCollection.AddSingleton(ServerConfigurationManager);
  621. var assemblyInfo = new AssemblyInfo();
  622. serviceCollection.AddSingleton<IAssemblyInfo>(assemblyInfo);
  623. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LoggerFactory);
  624. await LocalizationManager.LoadAll();
  625. serviceCollection.AddSingleton<ILocalizationManager>(LocalizationManager);
  626. serviceCollection.AddSingleton<IBlurayExaminer>(new BdInfoExaminer(FileSystemManager));
  627. serviceCollection.AddSingleton<IXmlReaderSettingsFactory>(new XmlReaderSettingsFactory());
  628. UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
  629. serviceCollection.AddSingleton(UserDataManager);
  630. UserRepository = GetUserRepository();
  631. // This is only needed for disposal purposes. If removing this, make sure to have the manager handle disposing it
  632. serviceCollection.AddSingleton(UserRepository);
  633. var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory, JsonSerializer, ApplicationPaths, FileSystemManager);
  634. serviceCollection.AddSingleton<IDisplayPreferencesRepository>(displayPreferencesRepo);
  635. ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory, assemblyInfo);
  636. serviceCollection.AddSingleton<IItemRepository>(ItemRepository);
  637. AuthenticationRepository = GetAuthenticationRepository();
  638. serviceCollection.AddSingleton(AuthenticationRepository);
  639. UserManager = new UserManager(LoggerFactory, ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager);
  640. serviceCollection.AddSingleton(UserManager);
  641. LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
  642. serviceCollection.AddSingleton(LibraryManager);
  643. // TODO wtaylor: investigate use of second music manager
  644. var musicManager = new MusicManager(LibraryManager);
  645. serviceCollection.AddSingleton<IMusicManager>(new MusicManager(LibraryManager));
  646. LibraryMonitor = new LibraryMonitor(LoggerFactory, LibraryManager, ServerConfigurationManager, FileSystemManager, EnvironmentInfo);
  647. serviceCollection.AddSingleton(LibraryMonitor);
  648. serviceCollection.AddSingleton<ISearchEngine>(new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  649. CertificateInfo = GetCertificateInfo(true);
  650. Certificate = GetCertificate(CertificateInfo);
  651. HttpServer = new HttpListenerHost(this,
  652. LoggerFactory,
  653. ServerConfigurationManager,
  654. _configuration,
  655. NetworkManager,
  656. JsonSerializer,
  657. XmlSerializer,
  658. CreateHttpListener());
  659. HttpServer.GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
  660. serviceCollection.AddSingleton(HttpServer);
  661. ImageProcessor = GetImageProcessor();
  662. serviceCollection.AddSingleton(ImageProcessor);
  663. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  664. serviceCollection.AddSingleton(TVSeriesManager);
  665. var encryptionManager = new EncryptionManager();
  666. serviceCollection.AddSingleton<IEncryptionManager>(encryptionManager);
  667. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager);
  668. serviceCollection.AddSingleton(DeviceManager);
  669. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
  670. serviceCollection.AddSingleton(MediaSourceManager);
  671. SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
  672. serviceCollection.AddSingleton(SubtitleManager);
  673. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  674. serviceCollection.AddSingleton(ProviderManager);
  675. DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ProviderManager, this, () => MediaSourceManager, () => LiveTvManager);
  676. serviceCollection.AddSingleton(DtoService);
  677. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager);
  678. serviceCollection.AddSingleton(ChannelManager);
  679. SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager);
  680. serviceCollection.AddSingleton(SessionManager);
  681. serviceCollection.AddSingleton<IDlnaManager>(
  682. new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this, assemblyInfo));
  683. CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
  684. serviceCollection.AddSingleton(CollectionManager);
  685. PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory, UserManager, ProviderManager);
  686. serviceCollection.AddSingleton(PlaylistManager);
  687. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
  688. serviceCollection.AddSingleton(LiveTvManager);
  689. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  690. serviceCollection.AddSingleton(UserViewManager);
  691. NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager);
  692. serviceCollection.AddSingleton(NotificationManager);
  693. serviceCollection.AddSingleton<IDeviceDiscovery>(
  694. new DeviceDiscovery(LoggerFactory, ServerConfigurationManager, SocketFactory));
  695. ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository);
  696. serviceCollection.AddSingleton(ChapterManager);
  697. RegisterMediaEncoder(serviceCollection);
  698. EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager);
  699. serviceCollection.AddSingleton(EncodingManager);
  700. var activityLogRepo = GetActivityLogRepository();
  701. serviceCollection.AddSingleton(activityLogRepo);
  702. serviceCollection.AddSingleton<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager));
  703. var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
  704. serviceCollection.AddSingleton<IAuthorizationContext>(authContext);
  705. serviceCollection.AddSingleton<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  706. AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, SessionManager, NetworkManager);
  707. serviceCollection.AddSingleton(AuthService);
  708. SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory);
  709. serviceCollection.AddSingleton(SubtitleEncoder);
  710. serviceCollection.AddSingleton(CreateResourceFileManager());
  711. displayPreferencesRepo.Initialize();
  712. var userDataRepo = new SqliteUserDataRepository(LoggerFactory, ApplicationPaths);
  713. SetStaticProperties();
  714. ((UserManager)UserManager).Initialize();
  715. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  716. ItemRepository.Initialize(userDataRepo, UserManager);
  717. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  718. _serviceProvider = serviceCollection.BuildServiceProvider();
  719. }
  720. protected virtual IBrotliCompressor CreateBrotliCompressor()
  721. {
  722. return null;
  723. }
  724. public virtual string PackageRuntime => "netcore";
  725. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, EnvironmentInfo.EnvironmentInfo environmentInfo)
  726. {
  727. // Distinct these to prevent users from reporting problems that aren't actually problems
  728. var commandLineArgs = Environment
  729. .GetCommandLineArgs()
  730. .Distinct();
  731. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  732. logger.LogInformation("Operating system: {OS} {OSVersion}", environmentInfo.OperatingSystemName, environmentInfo.OperatingSystemVersion);
  733. logger.LogInformation("Architecture: {Architecture}", environmentInfo.SystemArchitecture);
  734. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  735. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  736. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  737. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  738. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  739. }
  740. private void SetHttpLimit()
  741. {
  742. try
  743. {
  744. // Increase the max http request limit
  745. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  746. }
  747. catch (Exception ex)
  748. {
  749. Logger.LogError(ex, "Error setting http limit");
  750. }
  751. }
  752. protected virtual bool SupportsDualModeSockets => true;
  753. private X509Certificate GetCertificate(CertificateInfo info)
  754. {
  755. var certificateLocation = info == null ? null : info.Path;
  756. if (string.IsNullOrWhiteSpace(certificateLocation))
  757. {
  758. return null;
  759. }
  760. try
  761. {
  762. if (!File.Exists(certificateLocation))
  763. {
  764. return null;
  765. }
  766. // Don't use an empty string password
  767. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  768. var localCert = new X509Certificate2(certificateLocation, password);
  769. //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  770. if (!localCert.HasPrivateKey)
  771. {
  772. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  773. return null;
  774. }
  775. return localCert;
  776. }
  777. catch (Exception ex)
  778. {
  779. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  780. return null;
  781. }
  782. }
  783. private IImageProcessor GetImageProcessor()
  784. {
  785. return new ImageProcessor(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
  786. }
  787. protected virtual FFMpegInstallInfo GetFfmpegInstallInfo()
  788. {
  789. var info = new FFMpegInstallInfo();
  790. // Windows builds: http://ffmpeg.zeranoe.com/builds/
  791. // Linux builds: http://johnvansickle.com/ffmpeg/
  792. // OS X builds: http://ffmpegmac.net/
  793. // OS X x64: http://www.evermeet.cx/ffmpeg/
  794. if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Linux)
  795. {
  796. info.FFMpegFilename = "ffmpeg";
  797. info.FFProbeFilename = "ffprobe";
  798. info.ArchiveType = "7z";
  799. info.Version = "20170308";
  800. }
  801. else if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
  802. {
  803. info.FFMpegFilename = "ffmpeg.exe";
  804. info.FFProbeFilename = "ffprobe.exe";
  805. info.Version = "20170308";
  806. info.ArchiveType = "7z";
  807. }
  808. else if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
  809. {
  810. info.FFMpegFilename = "ffmpeg";
  811. info.FFProbeFilename = "ffprobe";
  812. info.ArchiveType = "7z";
  813. info.Version = "20170308";
  814. }
  815. return info;
  816. }
  817. protected virtual FFMpegInfo GetFFMpegInfo()
  818. {
  819. return new FFMpegLoader(ApplicationPaths, FileSystemManager, GetFfmpegInstallInfo())
  820. .GetFFMpegInfo(StartupOptions);
  821. }
  822. /// <summary>
  823. /// Registers the media encoder.
  824. /// </summary>
  825. /// <returns>Task.</returns>
  826. private void RegisterMediaEncoder(IServiceCollection serviceCollection)
  827. {
  828. string encoderPath = null;
  829. string probePath = null;
  830. var info = GetFFMpegInfo();
  831. encoderPath = info.EncoderPath;
  832. probePath = info.ProbePath;
  833. var hasExternalEncoder = string.Equals(info.Version, "external", StringComparison.OrdinalIgnoreCase);
  834. var mediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  835. LoggerFactory,
  836. JsonSerializer,
  837. encoderPath,
  838. probePath,
  839. hasExternalEncoder,
  840. ServerConfigurationManager,
  841. FileSystemManager,
  842. LiveTvManager,
  843. IsoManager,
  844. LibraryManager,
  845. ChannelManager,
  846. SessionManager,
  847. () => SubtitleEncoder,
  848. () => MediaSourceManager,
  849. HttpClient,
  850. ZipClient,
  851. ProcessFactory,
  852. 5000);
  853. MediaEncoder = mediaEncoder;
  854. serviceCollection.AddSingleton(MediaEncoder);
  855. }
  856. /// <summary>
  857. /// Gets the user repository.
  858. /// </summary>
  859. /// <returns>Task{IUserRepository}.</returns>
  860. private IUserRepository GetUserRepository()
  861. {
  862. var repo = new SqliteUserRepository(LoggerFactory, ApplicationPaths, JsonSerializer);
  863. repo.Initialize();
  864. return repo;
  865. }
  866. private IAuthenticationRepository GetAuthenticationRepository()
  867. {
  868. var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager);
  869. repo.Initialize();
  870. return repo;
  871. }
  872. private IActivityRepository GetActivityLogRepository()
  873. {
  874. var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager);
  875. repo.Initialize();
  876. return repo;
  877. }
  878. /// <summary>
  879. /// Dirty hacks
  880. /// </summary>
  881. private void SetStaticProperties()
  882. {
  883. ((SqliteItemRepository)ItemRepository).ImageProcessor = ImageProcessor;
  884. // For now there's no real way to inject these properly
  885. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  886. BaseItem.ConfigurationManager = ServerConfigurationManager;
  887. BaseItem.LibraryManager = LibraryManager;
  888. BaseItem.ProviderManager = ProviderManager;
  889. BaseItem.LocalizationManager = LocalizationManager;
  890. BaseItem.ItemRepository = ItemRepository;
  891. User.UserManager = UserManager;
  892. BaseItem.FileSystem = FileSystemManager;
  893. BaseItem.UserDataManager = UserDataManager;
  894. BaseItem.ChannelManager = ChannelManager;
  895. Video.LiveTvManager = LiveTvManager;
  896. Folder.UserViewManager = UserViewManager;
  897. UserView.TVSeriesManager = TVSeriesManager;
  898. UserView.PlaylistManager = PlaylistManager;
  899. UserView.CollectionManager = CollectionManager;
  900. BaseItem.MediaSourceManager = MediaSourceManager;
  901. CollectionFolder.XmlSerializer = XmlSerializer;
  902. CollectionFolder.JsonSerializer = JsonSerializer;
  903. CollectionFolder.ApplicationHost = this;
  904. AuthenticatedAttribute.AuthService = AuthService;
  905. }
  906. /// <summary>
  907. /// Finds the parts.
  908. /// </summary>
  909. protected void FindParts()
  910. {
  911. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  912. {
  913. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  914. ConfigurationManager.SaveConfiguration();
  915. }
  916. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  917. Plugins = GetExports<IPlugin>()
  918. .Select(LoadPlugin)
  919. .Where(i => i != null)
  920. .ToArray();
  921. HttpServer.Init(GetExports<IService>(false), GetExports<IWebSocketListener>());
  922. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  923. GetExports<IItemResolver>(),
  924. GetExports<IIntroProvider>(),
  925. GetExports<IBaseItemComparer>(),
  926. GetExports<ILibraryPostScanTask>());
  927. ProviderManager.AddParts(GetExports<IImageProvider>(),
  928. GetExports<IMetadataService>(),
  929. GetExports<IMetadataProvider>(),
  930. GetExports<IMetadataSaver>(),
  931. GetExports<IExternalId>());
  932. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  933. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  934. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  935. ChannelManager.AddParts(GetExports<IChannel>());
  936. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  937. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  938. UserManager.AddParts(GetExports<IAuthenticationProvider>());
  939. IsoManager.AddParts(GetExports<IIsoMounter>());
  940. }
  941. private IPlugin LoadPlugin(IPlugin plugin)
  942. {
  943. try
  944. {
  945. if (plugin is IPluginAssembly assemblyPlugin)
  946. {
  947. var assembly = plugin.GetType().Assembly;
  948. var assemblyName = assembly.GetName();
  949. var assemblyFilePath = assembly.Location;
  950. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  951. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  952. try
  953. {
  954. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  955. if (idAttributes.Length > 0)
  956. {
  957. var attribute = (GuidAttribute)idAttributes[0];
  958. var assemblyId = new Guid(attribute.Value);
  959. assemblyPlugin.SetId(assemblyId);
  960. }
  961. }
  962. catch (Exception ex)
  963. {
  964. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  965. }
  966. }
  967. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  968. {
  969. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  970. }
  971. }
  972. catch (Exception ex)
  973. {
  974. Logger.LogError(ex, "Error loading plugin {pluginName}", plugin.GetType().FullName);
  975. return null;
  976. }
  977. return plugin;
  978. }
  979. /// <summary>
  980. /// Discovers the types.
  981. /// </summary>
  982. protected void DiscoverTypes()
  983. {
  984. Logger.LogInformation("Loading assemblies");
  985. AllConcreteTypes = GetComposablePartAssemblies()
  986. .SelectMany(x => x.ExportedTypes)
  987. .Where(type =>
  988. {
  989. return type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType;
  990. })
  991. .ToArray();
  992. }
  993. private CertificateInfo CertificateInfo { get; set; }
  994. protected X509Certificate Certificate { get; private set; }
  995. private IEnumerable<string> GetUrlPrefixes()
  996. {
  997. var hosts = new[] { "+" };
  998. return hosts.SelectMany(i =>
  999. {
  1000. var prefixes = new List<string>
  1001. {
  1002. "http://"+i+":" + HttpPort + "/"
  1003. };
  1004. if (CertificateInfo != null)
  1005. {
  1006. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  1007. }
  1008. return prefixes;
  1009. });
  1010. }
  1011. protected IHttpListener CreateHttpListener() => new WebSocketSharpListener(Logger);
  1012. private CertificateInfo GetCertificateInfo(bool generateCertificate)
  1013. {
  1014. if (!string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.CertificatePath))
  1015. {
  1016. // Custom cert
  1017. return new CertificateInfo
  1018. {
  1019. Path = ServerConfigurationManager.Configuration.CertificatePath,
  1020. Password = ServerConfigurationManager.Configuration.CertificatePassword
  1021. };
  1022. }
  1023. // Generate self-signed cert
  1024. var certHost = GetHostnameFromExternalDns(ServerConfigurationManager.Configuration.WanDdns);
  1025. var certPath = Path.Combine(ServerConfigurationManager.ApplicationPaths.ProgramDataPath, "ssl", "cert_" + (certHost + "2").GetMD5().ToString("N") + ".pfx");
  1026. var password = "embycert";
  1027. //if (generateCertificate)
  1028. //{
  1029. // if (!File.Exists(certPath))
  1030. // {
  1031. // FileSystemManager.CreateDirectory(FileSystemManager.GetDirectoryName(certPath));
  1032. // try
  1033. // {
  1034. // CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, password, Logger);
  1035. // }
  1036. // catch (Exception ex)
  1037. // {
  1038. // Logger.LogError(ex, "Error creating ssl cert");
  1039. // return null;
  1040. // }
  1041. // }
  1042. //}
  1043. return new CertificateInfo
  1044. {
  1045. Path = certPath,
  1046. Password = password
  1047. };
  1048. }
  1049. /// <summary>
  1050. /// Called when [configuration updated].
  1051. /// </summary>
  1052. /// <param name="sender">The sender.</param>
  1053. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  1054. protected void OnConfigurationUpdated(object sender, EventArgs e)
  1055. {
  1056. var requiresRestart = false;
  1057. // Don't do anything if these haven't been set yet
  1058. if (HttpPort != 0 && HttpsPort != 0)
  1059. {
  1060. // Need to restart if ports have changed
  1061. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  1062. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  1063. {
  1064. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  1065. {
  1066. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  1067. ServerConfigurationManager.SaveConfiguration();
  1068. requiresRestart = true;
  1069. }
  1070. }
  1071. }
  1072. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  1073. {
  1074. requiresRestart = true;
  1075. }
  1076. var currentCertPath = CertificateInfo == null ? null : CertificateInfo.Path;
  1077. var newCertInfo = GetCertificateInfo(false);
  1078. var newCertPath = newCertInfo == null ? null : newCertInfo.Path;
  1079. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  1080. {
  1081. requiresRestart = true;
  1082. }
  1083. if (requiresRestart)
  1084. {
  1085. Logger.LogInformation("App needs to be restarted due to configuration change.");
  1086. NotifyPendingRestart();
  1087. }
  1088. }
  1089. /// <summary>
  1090. /// Notifies that the kernel that a change has been made that requires a restart
  1091. /// </summary>
  1092. public void NotifyPendingRestart()
  1093. {
  1094. Logger.LogInformation("App needs to be restarted.");
  1095. var changed = !HasPendingRestart;
  1096. HasPendingRestart = true;
  1097. if (changed)
  1098. {
  1099. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  1100. }
  1101. }
  1102. /// <summary>
  1103. /// Restarts this instance.
  1104. /// </summary>
  1105. public void Restart()
  1106. {
  1107. if (!CanSelfRestart)
  1108. {
  1109. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  1110. }
  1111. if (IsShuttingDown)
  1112. {
  1113. return;
  1114. }
  1115. IsShuttingDown = true;
  1116. Task.Run(async () =>
  1117. {
  1118. try
  1119. {
  1120. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  1121. }
  1122. catch (Exception ex)
  1123. {
  1124. Logger.LogError(ex, "Error sending server restart notification");
  1125. }
  1126. Logger.LogInformation("Calling RestartInternal");
  1127. RestartInternal();
  1128. });
  1129. }
  1130. protected abstract void RestartInternal();
  1131. /// <summary>
  1132. /// Gets the composable part assemblies.
  1133. /// </summary>
  1134. /// <returns>IEnumerable{Assembly}.</returns>
  1135. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  1136. {
  1137. if (Directory.Exists(ApplicationPaths.PluginsPath))
  1138. {
  1139. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly))
  1140. {
  1141. Logger.LogInformation("Loading assembly {Path}", file);
  1142. yield return Assembly.LoadFrom(file);
  1143. }
  1144. }
  1145. // Include composable parts in the Api assembly
  1146. yield return typeof(ApiEntryPoint).Assembly;
  1147. // Include composable parts in the Dashboard assembly
  1148. yield return typeof(DashboardService).Assembly;
  1149. // Include composable parts in the Model assembly
  1150. yield return typeof(SystemInfo).Assembly;
  1151. // Include composable parts in the Common assembly
  1152. yield return typeof(IApplicationHost).Assembly;
  1153. // Include composable parts in the Controller assembly
  1154. yield return typeof(IServerApplicationHost).Assembly;
  1155. // Include composable parts in the Providers assembly
  1156. yield return typeof(ProviderUtils).Assembly;
  1157. // Include composable parts in the Photos assembly
  1158. yield return typeof(PhotoProvider).Assembly;
  1159. // Emby.Server implementations
  1160. yield return typeof(InstallationManager).Assembly;
  1161. // MediaEncoding
  1162. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  1163. // Dlna
  1164. yield return typeof(DlnaEntryPoint).Assembly;
  1165. // Local metadata
  1166. yield return typeof(BoxSetXmlSaver).Assembly;
  1167. // Notifications
  1168. yield return typeof(NotificationManager).Assembly;
  1169. // Xbmc
  1170. yield return typeof(ArtistNfoProvider).Assembly;
  1171. foreach (var i in GetAssembliesWithPartsInternal())
  1172. {
  1173. yield return i;
  1174. }
  1175. }
  1176. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  1177. /// <summary>
  1178. /// Gets the system status.
  1179. /// </summary>
  1180. /// <returns>SystemInfo.</returns>
  1181. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  1182. {
  1183. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1184. var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false);
  1185. return new SystemInfo
  1186. {
  1187. HasPendingRestart = HasPendingRestart,
  1188. IsShuttingDown = IsShuttingDown,
  1189. Version = ApplicationVersion,
  1190. ProductName = ApplicationProductName,
  1191. WebSocketPortNumber = HttpPort,
  1192. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  1193. Id = SystemId,
  1194. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1195. LogPath = ApplicationPaths.LogDirectoryPath,
  1196. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1197. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1198. CachePath = ApplicationPaths.CachePath,
  1199. HttpServerPortNumber = HttpPort,
  1200. SupportsHttps = SupportsHttps,
  1201. HttpsPortNumber = HttpsPort,
  1202. OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(),
  1203. OperatingSystemDisplayName = EnvironmentInfo.OperatingSystemName,
  1204. CanSelfRestart = CanSelfRestart,
  1205. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1206. WanAddress = wanAddress,
  1207. HasUpdateAvailable = HasUpdateAvailable,
  1208. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  1209. ServerName = FriendlyName,
  1210. LocalAddress = localAddress,
  1211. SupportsLibraryMonitor = true,
  1212. EncoderLocationType = MediaEncoder.EncoderLocationType,
  1213. SystemArchitecture = EnvironmentInfo.SystemArchitecture,
  1214. SystemUpdateLevel = SystemUpdateLevel,
  1215. PackageName = StartupOptions.PackageName
  1216. };
  1217. }
  1218. public WakeOnLanInfo[] GetWakeOnLanInfo()
  1219. {
  1220. return NetworkManager.GetMacAddresses()
  1221. .Select(i => new WakeOnLanInfo
  1222. {
  1223. MacAddress = i
  1224. })
  1225. .ToArray();
  1226. }
  1227. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1228. {
  1229. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1230. var wanAddress = await GetWanApiUrl(cancellationToken).ConfigureAwait(false);
  1231. return new PublicSystemInfo
  1232. {
  1233. Version = ApplicationVersion,
  1234. Id = SystemId,
  1235. OperatingSystem = EnvironmentInfo.OperatingSystem.ToString(),
  1236. WanAddress = wanAddress,
  1237. ServerName = FriendlyName,
  1238. LocalAddress = localAddress
  1239. };
  1240. }
  1241. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1242. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1243. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1244. {
  1245. try
  1246. {
  1247. // Return the first matched address, if found, or the first known local address
  1248. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1249. foreach (var address in addresses)
  1250. {
  1251. return GetLocalApiUrl(address);
  1252. }
  1253. return null;
  1254. }
  1255. catch (Exception ex)
  1256. {
  1257. Logger.LogError(ex, "Error getting local Ip address information");
  1258. }
  1259. return null;
  1260. }
  1261. public async Task<string> GetWanApiUrl(CancellationToken cancellationToken)
  1262. {
  1263. const string url = "http://ipv4.icanhazip.com";
  1264. try
  1265. {
  1266. using (var response = await HttpClient.Get(new HttpRequestOptions
  1267. {
  1268. Url = url,
  1269. LogErrorResponseBody = false,
  1270. LogErrors = false,
  1271. LogRequest = false,
  1272. TimeoutMs = 10000,
  1273. BufferContent = false,
  1274. CancellationToken = cancellationToken
  1275. }))
  1276. {
  1277. return GetLocalApiUrl(response.ReadToEnd().Trim());
  1278. }
  1279. }
  1280. catch (Exception ex)
  1281. {
  1282. Logger.LogError(ex, "Error getting WAN Ip address information");
  1283. }
  1284. return null;
  1285. }
  1286. public string GetLocalApiUrl(IpAddressInfo ipAddress)
  1287. {
  1288. if (ipAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
  1289. {
  1290. return GetLocalApiUrl("[" + ipAddress.Address + "]");
  1291. }
  1292. return GetLocalApiUrl(ipAddress.Address);
  1293. }
  1294. public string GetLocalApiUrl(string host)
  1295. {
  1296. return string.Format("http://{0}:{1}",
  1297. host,
  1298. HttpPort.ToString(CultureInfo.InvariantCulture));
  1299. }
  1300. public Task<List<IpAddressInfo>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1301. {
  1302. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1303. }
  1304. private async Task<List<IpAddressInfo>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1305. {
  1306. var addresses = ServerConfigurationManager
  1307. .Configuration
  1308. .LocalNetworkAddresses
  1309. .Select(NormalizeConfiguredLocalAddress)
  1310. .Where(i => i != null)
  1311. .ToList();
  1312. if (addresses.Count == 0)
  1313. {
  1314. addresses.AddRange(NetworkManager.GetLocalIpAddresses());
  1315. }
  1316. var resultList = new List<IpAddressInfo>();
  1317. foreach (var address in addresses)
  1318. {
  1319. if (!allowLoopback)
  1320. {
  1321. if (address.Equals(IpAddressInfo.Loopback) || address.Equals(IpAddressInfo.IPv6Loopback))
  1322. {
  1323. continue;
  1324. }
  1325. }
  1326. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1327. if (valid)
  1328. {
  1329. resultList.Add(address);
  1330. if (limit > 0 && resultList.Count >= limit)
  1331. {
  1332. return resultList;
  1333. }
  1334. }
  1335. }
  1336. return resultList;
  1337. }
  1338. private IpAddressInfo NormalizeConfiguredLocalAddress(string address)
  1339. {
  1340. var index = address.Trim('/').IndexOf('/');
  1341. if (index != -1)
  1342. {
  1343. address = address.Substring(index + 1);
  1344. }
  1345. if (NetworkManager.TryParseIpAddress(address.Trim('/'), out IpAddressInfo result))
  1346. {
  1347. return result;
  1348. }
  1349. return null;
  1350. }
  1351. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1352. private async Task<bool> IsIpAddressValidAsync(IpAddressInfo address, CancellationToken cancellationToken)
  1353. {
  1354. if (address.Equals(IpAddressInfo.Loopback) ||
  1355. address.Equals(IpAddressInfo.IPv6Loopback))
  1356. {
  1357. return true;
  1358. }
  1359. var apiUrl = GetLocalApiUrl(address);
  1360. apiUrl += "/system/ping";
  1361. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1362. {
  1363. return cachedResult;
  1364. }
  1365. var logPing = false;
  1366. #if DEBUG
  1367. logPing = true;
  1368. #endif
  1369. try
  1370. {
  1371. using (var response = await HttpClient.SendAsync(new HttpRequestOptions
  1372. {
  1373. Url = apiUrl,
  1374. LogErrorResponseBody = false,
  1375. LogErrors = logPing,
  1376. LogRequest = logPing,
  1377. TimeoutMs = 5000,
  1378. BufferContent = false,
  1379. CancellationToken = cancellationToken
  1380. }, "POST").ConfigureAwait(false))
  1381. {
  1382. using (var reader = new StreamReader(response.Content))
  1383. {
  1384. var result = reader.ReadToEnd();
  1385. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1386. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1387. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1388. return valid;
  1389. }
  1390. }
  1391. }
  1392. catch (OperationCanceledException)
  1393. {
  1394. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1395. throw;
  1396. }
  1397. catch (Exception ex)
  1398. {
  1399. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1400. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1401. return false;
  1402. }
  1403. }
  1404. public string FriendlyName =>
  1405. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1406. ? Environment.MachineName
  1407. : ServerConfigurationManager.Configuration.ServerName;
  1408. public int HttpPort { get; private set; }
  1409. public int HttpsPort { get; private set; }
  1410. /// <summary>
  1411. /// Shuts down.
  1412. /// </summary>
  1413. public async Task Shutdown()
  1414. {
  1415. if (IsShuttingDown)
  1416. {
  1417. return;
  1418. }
  1419. IsShuttingDown = true;
  1420. try
  1421. {
  1422. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1423. }
  1424. catch (Exception ex)
  1425. {
  1426. Logger.LogError(ex, "Error sending server shutdown notification");
  1427. }
  1428. ShutdownInternal();
  1429. }
  1430. protected abstract void ShutdownInternal();
  1431. public event EventHandler HasUpdateAvailableChanged;
  1432. private bool _hasUpdateAvailable;
  1433. public bool HasUpdateAvailable
  1434. {
  1435. get => _hasUpdateAvailable;
  1436. set
  1437. {
  1438. var fireEvent = value && !_hasUpdateAvailable;
  1439. _hasUpdateAvailable = value;
  1440. if (fireEvent)
  1441. {
  1442. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1443. }
  1444. }
  1445. }
  1446. /// <summary>
  1447. /// Removes the plugin.
  1448. /// </summary>
  1449. /// <param name="plugin">The plugin.</param>
  1450. public void RemovePlugin(IPlugin plugin)
  1451. {
  1452. var list = Plugins.ToList();
  1453. list.Remove(plugin);
  1454. Plugins = list.ToArray();
  1455. }
  1456. /// <summary>
  1457. /// This returns localhost in the case of no external dns, and the hostname if the
  1458. /// dns is prefixed with a valid Uri prefix.
  1459. /// </summary>
  1460. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  1461. /// <returns>The hostname in <paramref name="externalDns"/></returns>
  1462. private static string GetHostnameFromExternalDns(string externalDns)
  1463. {
  1464. if (string.IsNullOrEmpty(externalDns))
  1465. {
  1466. return "localhost";
  1467. }
  1468. try
  1469. {
  1470. return new Uri(externalDns).Host;
  1471. }
  1472. catch
  1473. {
  1474. return externalDns;
  1475. }
  1476. }
  1477. public virtual void LaunchUrl(string url)
  1478. {
  1479. if (!CanLaunchWebBrowser)
  1480. {
  1481. throw new NotSupportedException();
  1482. }
  1483. var process = ProcessFactory.Create(new ProcessOptions
  1484. {
  1485. FileName = url,
  1486. //EnableRaisingEvents = true,
  1487. UseShellExecute = true,
  1488. ErrorDialog = false
  1489. });
  1490. process.Exited += ProcessExited;
  1491. try
  1492. {
  1493. process.Start();
  1494. }
  1495. catch (Exception ex)
  1496. {
  1497. Logger.LogError(ex, "Error launching url: {url}", url);
  1498. throw;
  1499. }
  1500. }
  1501. private static void ProcessExited(object sender, EventArgs e)
  1502. {
  1503. ((IProcess)sender).Dispose();
  1504. }
  1505. public virtual void EnableLoopback(string appName)
  1506. {
  1507. }
  1508. /// <summary>
  1509. /// Called when [application updated].
  1510. /// </summary>
  1511. /// <param name="package">The package.</param>
  1512. protected void OnApplicationUpdated(PackageVersionInfo package)
  1513. {
  1514. Logger.LogInformation("Application has been updated to version {0}", package.versionStr);
  1515. ApplicationUpdated?.Invoke(this, new GenericEventArgs<PackageVersionInfo>
  1516. {
  1517. Argument = package
  1518. });
  1519. NotifyPendingRestart();
  1520. }
  1521. private bool _disposed;
  1522. /// <summary>
  1523. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1524. /// </summary>
  1525. public void Dispose()
  1526. {
  1527. if (!_disposed)
  1528. {
  1529. _disposed = true;
  1530. Dispose(true);
  1531. }
  1532. }
  1533. /// <summary>
  1534. /// Releases unmanaged and - optionally - managed resources.
  1535. /// </summary>
  1536. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1537. protected virtual void Dispose(bool dispose)
  1538. {
  1539. if (dispose)
  1540. {
  1541. var type = GetType();
  1542. Logger.LogInformation("Disposing {Type}", type.Name);
  1543. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1544. DisposableParts.Clear();
  1545. foreach (var part in parts)
  1546. {
  1547. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1548. try
  1549. {
  1550. part.Dispose();
  1551. }
  1552. catch (Exception ex)
  1553. {
  1554. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1555. }
  1556. }
  1557. }
  1558. }
  1559. }
  1560. internal class CertificateInfo
  1561. {
  1562. public string Path { get; set; }
  1563. public string Password { get; set; }
  1564. }
  1565. }