ApplicationHost.cs 72 KB

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