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