ApplicationHost.cs 70 KB

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