ApplicationHost.cs 71 KB

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