2
0

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