ApplicationHost.cs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927
  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. /// <summary>
  124. /// Gets a value indicating whether this instance can self restart.
  125. /// </summary>
  126. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  127. public abstract bool CanSelfRestart { get; }
  128. public virtual bool CanLaunchWebBrowser
  129. {
  130. get
  131. {
  132. if (!Environment.UserInteractive)
  133. {
  134. return false;
  135. }
  136. if (StartupOptions.IsService)
  137. {
  138. return false;
  139. }
  140. if (OperatingSystem.Id == OperatingSystemId.Windows
  141. || OperatingSystem.Id == OperatingSystemId.Darwin)
  142. {
  143. return true;
  144. }
  145. return false;
  146. }
  147. }
  148. /// <summary>
  149. /// Occurs when [has pending restart changed].
  150. /// </summary>
  151. public event EventHandler HasPendingRestartChanged;
  152. /// <summary>
  153. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  154. /// </summary>
  155. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  156. public bool HasPendingRestart { get; private set; }
  157. public bool IsShuttingDown { get; private set; }
  158. /// <summary>
  159. /// Gets or sets the logger.
  160. /// </summary>
  161. /// <value>The logger.</value>
  162. protected ILogger Logger { get; set; }
  163. private IPlugin[] _plugins;
  164. /// <summary>
  165. /// Gets the plugins.
  166. /// </summary>
  167. /// <value>The plugins.</value>
  168. public IPlugin[] Plugins
  169. {
  170. get => _plugins;
  171. protected set => _plugins = value;
  172. }
  173. /// <summary>
  174. /// Gets or sets the logger factory.
  175. /// </summary>
  176. /// <value>The logger factory.</value>
  177. public ILoggerFactory LoggerFactory { get; protected set; }
  178. /// <summary>
  179. /// Gets or sets the application paths.
  180. /// </summary>
  181. /// <value>The application paths.</value>
  182. protected ServerApplicationPaths ApplicationPaths { get; set; }
  183. /// <summary>
  184. /// Gets or sets all concrete types.
  185. /// </summary>
  186. /// <value>All concrete types.</value>
  187. public Type[] AllConcreteTypes { get; protected set; }
  188. /// <summary>
  189. /// The disposable parts
  190. /// </summary>
  191. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  192. /// <summary>
  193. /// Gets the configuration manager.
  194. /// </summary>
  195. /// <value>The configuration manager.</value>
  196. protected IConfigurationManager ConfigurationManager { get; set; }
  197. public IFileSystem FileSystemManager { get; set; }
  198. public PackageVersionClass SystemUpdateLevel
  199. {
  200. get
  201. {
  202. #if BETA
  203. return PackageVersionClass.Beta;
  204. #else
  205. return PackageVersionClass.Release;
  206. #endif
  207. }
  208. }
  209. protected IServiceProvider _serviceProvider;
  210. /// <summary>
  211. /// Gets the server configuration manager.
  212. /// </summary>
  213. /// <value>The server configuration manager.</value>
  214. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  215. /// <summary>
  216. /// Gets or sets the user manager.
  217. /// </summary>
  218. /// <value>The user manager.</value>
  219. public IUserManager UserManager { get; set; }
  220. /// <summary>
  221. /// Gets or sets the library manager.
  222. /// </summary>
  223. /// <value>The library manager.</value>
  224. internal ILibraryManager LibraryManager { get; set; }
  225. /// <summary>
  226. /// Gets or sets the directory watchers.
  227. /// </summary>
  228. /// <value>The directory watchers.</value>
  229. private ILibraryMonitor LibraryMonitor { get; set; }
  230. /// <summary>
  231. /// Gets or sets the provider manager.
  232. /// </summary>
  233. /// <value>The provider manager.</value>
  234. private IProviderManager ProviderManager { get; set; }
  235. /// <summary>
  236. /// Gets or sets the HTTP server.
  237. /// </summary>
  238. /// <value>The HTTP server.</value>
  239. private IHttpServer HttpServer { get; set; }
  240. private IDtoService DtoService { get; set; }
  241. public IImageProcessor ImageProcessor { get; set; }
  242. /// <summary>
  243. /// Gets or sets the media encoder.
  244. /// </summary>
  245. /// <value>The media encoder.</value>
  246. private IMediaEncoder MediaEncoder { get; set; }
  247. private ISubtitleEncoder SubtitleEncoder { get; set; }
  248. private ISessionManager SessionManager { get; set; }
  249. private ILiveTvManager LiveTvManager { get; set; }
  250. public LocalizationManager LocalizationManager { get; set; }
  251. private IEncodingManager EncodingManager { get; set; }
  252. private IChannelManager ChannelManager { get; set; }
  253. /// <summary>
  254. /// Gets or sets the user data repository.
  255. /// </summary>
  256. /// <value>The user data repository.</value>
  257. private IUserDataManager UserDataManager { get; set; }
  258. private IUserRepository UserRepository { get; set; }
  259. internal SqliteItemRepository ItemRepository { get; set; }
  260. private INotificationManager NotificationManager { get; set; }
  261. private ISubtitleManager SubtitleManager { get; set; }
  262. private IChapterManager ChapterManager { get; set; }
  263. private IDeviceManager DeviceManager { get; set; }
  264. internal IUserViewManager UserViewManager { get; set; }
  265. private IAuthenticationRepository AuthenticationRepository { get; set; }
  266. private ITVSeriesManager TVSeriesManager { get; set; }
  267. private ICollectionManager CollectionManager { get; set; }
  268. private IMediaSourceManager MediaSourceManager { get; set; }
  269. private IPlaylistManager PlaylistManager { get; set; }
  270. private readonly IConfiguration _configuration;
  271. /// <summary>
  272. /// Gets or sets the installation manager.
  273. /// </summary>
  274. /// <value>The installation manager.</value>
  275. protected IInstallationManager InstallationManager { get; private set; }
  276. /// <summary>
  277. /// Gets or sets the zip client.
  278. /// </summary>
  279. /// <value>The zip client.</value>
  280. protected IZipClient ZipClient { get; private set; }
  281. protected IHttpResultFactory HttpResultFactory { get; private set; }
  282. protected IAuthService AuthService { get; private set; }
  283. public IStartupOptions StartupOptions { get; }
  284. internal IImageEncoder ImageEncoder { get; private set; }
  285. protected IProcessFactory ProcessFactory { get; private set; }
  286. protected readonly IXmlSerializer XmlSerializer;
  287. protected ISocketFactory SocketFactory { get; private set; }
  288. protected ITaskManager TaskManager { get; private set; }
  289. public IHttpClient HttpClient { get; private set; }
  290. protected INetworkManager NetworkManager { get; set; }
  291. public IJsonSerializer JsonSerializer { get; private set; }
  292. protected IIsoManager IsoManager { get; private set; }
  293. /// <summary>
  294. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  295. /// </summary>
  296. public ApplicationHost(
  297. ServerApplicationPaths applicationPaths,
  298. ILoggerFactory loggerFactory,
  299. IStartupOptions options,
  300. IFileSystem fileSystem,
  301. IImageEncoder imageEncoder,
  302. INetworkManager networkManager,
  303. IConfiguration configuration)
  304. {
  305. _configuration = configuration;
  306. XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory);
  307. NetworkManager = networkManager;
  308. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  309. ApplicationPaths = applicationPaths;
  310. LoggerFactory = loggerFactory;
  311. FileSystemManager = fileSystem;
  312. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager);
  313. Logger = LoggerFactory.CreateLogger("App");
  314. StartupOptions = options;
  315. ImageEncoder = imageEncoder;
  316. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  317. NetworkManager.NetworkChanged += OnNetworkChanged;
  318. }
  319. public string ExpandVirtualPath(string path)
  320. {
  321. var appPaths = ApplicationPaths;
  322. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  323. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  324. }
  325. public string ReverseVirtualPath(string path)
  326. {
  327. var appPaths = ApplicationPaths;
  328. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  329. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  330. }
  331. private string[] GetConfiguredLocalSubnets()
  332. {
  333. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  334. }
  335. private void OnNetworkChanged(object sender, EventArgs e)
  336. {
  337. _validAddressResults.Clear();
  338. }
  339. public string ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
  340. /// <summary>
  341. /// Gets the current application user agent.
  342. /// </summary>
  343. /// <value>The application user agent.</value>
  344. public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersion;
  345. /// <summary>
  346. /// Gets the email address for use within a comment section of a user agent field.
  347. /// Presently used to provide contact information to MusicBrainz service.
  348. /// </summary>
  349. public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
  350. /// <summary>
  351. /// Gets the current application name.
  352. /// </summary>
  353. /// <value>The application name.</value>
  354. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  355. private DeviceId _deviceId;
  356. public string SystemId
  357. {
  358. get
  359. {
  360. if (_deviceId == null)
  361. {
  362. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  363. }
  364. return _deviceId.Value;
  365. }
  366. }
  367. /// <summary>
  368. /// Gets the name.
  369. /// </summary>
  370. /// <value>The name.</value>
  371. public string Name => ApplicationProductName;
  372. /// <summary>
  373. /// Creates an instance of type and resolves all constructor dependencies
  374. /// </summary>
  375. /// <param name="type">The type.</param>
  376. /// <returns>System.Object.</returns>
  377. public object CreateInstance(Type type)
  378. => ActivatorUtilities.CreateInstance(_serviceProvider, type);
  379. /// <summary>
  380. /// Creates an instance of type and resolves all constructor dependencies
  381. /// </summary>
  382. /// /// <typeparam name="T">The type.</typeparam>
  383. /// <returns>T.</returns>
  384. public T CreateInstance<T>()
  385. => ActivatorUtilities.CreateInstance<T>(_serviceProvider);
  386. /// <summary>
  387. /// Creates the instance safe.
  388. /// </summary>
  389. /// <param name="type">The type.</param>
  390. /// <returns>System.Object.</returns>
  391. protected object CreateInstanceSafe(Type type)
  392. {
  393. try
  394. {
  395. Logger.LogDebug("Creating instance of {Type}", type);
  396. return ActivatorUtilities.CreateInstance(_serviceProvider, type);
  397. }
  398. catch (Exception ex)
  399. {
  400. Logger.LogError(ex, "Error creating {Type}", type);
  401. return null;
  402. }
  403. }
  404. /// <summary>
  405. /// Resolves this instance.
  406. /// </summary>
  407. /// <typeparam name="T">The type</typeparam>
  408. /// <returns>``0.</returns>
  409. public T Resolve<T>() => _serviceProvider.GetService<T>();
  410. /// <summary>
  411. /// Gets the export types.
  412. /// </summary>
  413. /// <typeparam name="T">The type</typeparam>
  414. /// <returns>IEnumerable{Type}.</returns>
  415. public IEnumerable<Type> GetExportTypes<T>()
  416. {
  417. var currentType = typeof(T);
  418. return AllConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  419. }
  420. /// <summary>
  421. /// Gets the exports.
  422. /// </summary>
  423. /// <typeparam name="T">The type</typeparam>
  424. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  425. /// <returns>IEnumerable{``0}.</returns>
  426. public IEnumerable<T> GetExports<T>(bool manageLifetime = true)
  427. {
  428. var parts = GetExportTypes<T>()
  429. .Select(CreateInstanceSafe)
  430. .Where(i => i != null)
  431. .Cast<T>()
  432. .ToList(); // Convert to list so this isn't executed for each iteration
  433. if (manageLifetime)
  434. {
  435. lock (_disposableParts)
  436. {
  437. _disposableParts.AddRange(parts.OfType<IDisposable>());
  438. }
  439. }
  440. return parts;
  441. }
  442. /// <summary>
  443. /// Runs the startup tasks.
  444. /// </summary>
  445. public async Task RunStartupTasksAsync()
  446. {
  447. Logger.LogInformation("Running startup tasks");
  448. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  449. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  450. MediaEncoder.SetFFmpegPath();
  451. Logger.LogInformation("ServerId: {0}", SystemId);
  452. var entryPoints = GetExports<IServerEntryPoint>().ToList();
  453. var stopWatch = new Stopwatch();
  454. stopWatch.Start();
  455. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  456. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  457. Logger.LogInformation("Core startup complete");
  458. HttpServer.GlobalResponse = null;
  459. stopWatch.Restart();
  460. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  461. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  462. stopWatch.Stop();
  463. }
  464. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  465. {
  466. foreach (var entryPoint in entryPoints)
  467. {
  468. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  469. {
  470. continue;
  471. }
  472. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  473. yield return entryPoint.RunAsync();
  474. }
  475. }
  476. public async Task InitAsync(IServiceCollection serviceCollection)
  477. {
  478. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  479. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  480. // Safeguard against invalid configuration
  481. if (HttpPort == HttpsPort)
  482. {
  483. HttpPort = ServerConfiguration.DefaultHttpPort;
  484. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  485. }
  486. JsonSerializer = new JsonSerializer(FileSystemManager);
  487. if (Plugins != null)
  488. {
  489. var pluginBuilder = new StringBuilder();
  490. foreach (var plugin in Plugins)
  491. {
  492. pluginBuilder.AppendLine(
  493. string.Format(
  494. CultureInfo.InvariantCulture,
  495. "{0} {1}",
  496. plugin.Name,
  497. plugin.Version));
  498. }
  499. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  500. }
  501. DiscoverTypes();
  502. await RegisterResources(serviceCollection).ConfigureAwait(false);
  503. FindParts();
  504. string contentRoot = ServerConfigurationManager.Configuration.DashboardSourcePath;
  505. if (string.IsNullOrEmpty(contentRoot))
  506. {
  507. contentRoot = ServerConfigurationManager.ApplicationPaths.WebPath;
  508. }
  509. var host = new WebHostBuilder()
  510. .UseKestrel(options =>
  511. {
  512. options.ListenAnyIP(HttpPort);
  513. if (EnableHttps && Certificate != null)
  514. {
  515. options.ListenAnyIP(HttpsPort, listenOptions => listenOptions.UseHttps(Certificate));
  516. }
  517. })
  518. .UseContentRoot(contentRoot)
  519. .ConfigureServices(services =>
  520. {
  521. services.AddResponseCompression();
  522. services.AddHttpContextAccessor();
  523. })
  524. .Configure(app =>
  525. {
  526. app.UseWebSockets();
  527. app.UseResponseCompression();
  528. // TODO app.UseMiddleware<WebSocketMiddleware>();
  529. app.Use(ExecuteWebsocketHandlerAsync);
  530. app.Use(ExecuteHttpHandlerAsync);
  531. })
  532. .Build();
  533. await host.StartAsync().ConfigureAwait(false);
  534. }
  535. private async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func<Task> next)
  536. {
  537. if (!context.WebSockets.IsWebSocketRequest)
  538. {
  539. await next().ConfigureAwait(false);
  540. return;
  541. }
  542. await HttpServer.ProcessWebSocketRequest(context).ConfigureAwait(false);
  543. }
  544. private async Task ExecuteHttpHandlerAsync(HttpContext context, Func<Task> next)
  545. {
  546. if (context.WebSockets.IsWebSocketRequest)
  547. {
  548. await next().ConfigureAwait(false);
  549. return;
  550. }
  551. var request = context.Request;
  552. var response = context.Response;
  553. var localPath = context.Request.Path.ToString();
  554. var req = new WebSocketSharpRequest(request, response, request.Path, Logger);
  555. await HttpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted).ConfigureAwait(false);
  556. }
  557. public static IStreamHelper StreamHelper { get; set; }
  558. /// <summary>
  559. /// Registers resources that classes will depend on
  560. /// </summary>
  561. protected async Task RegisterResources(IServiceCollection serviceCollection)
  562. {
  563. serviceCollection.AddMemoryCache();
  564. serviceCollection.AddSingleton(ConfigurationManager);
  565. serviceCollection.AddSingleton<IApplicationHost>(this);
  566. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  567. serviceCollection.AddSingleton<IConfiguration>(_configuration);
  568. serviceCollection.AddSingleton(JsonSerializer);
  569. serviceCollection.AddSingleton(LoggerFactory);
  570. serviceCollection.AddLogging();
  571. serviceCollection.AddSingleton(Logger);
  572. serviceCollection.AddSingleton(FileSystemManager);
  573. serviceCollection.AddSingleton<TvDbClientManager>();
  574. HttpClient = new HttpClientManager.HttpClientManager(
  575. ApplicationPaths,
  576. LoggerFactory.CreateLogger<HttpClientManager.HttpClientManager>(),
  577. FileSystemManager,
  578. () => ApplicationUserAgent);
  579. serviceCollection.AddSingleton(HttpClient);
  580. serviceCollection.AddSingleton(NetworkManager);
  581. IsoManager = new IsoManager();
  582. serviceCollection.AddSingleton(IsoManager);
  583. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory, FileSystemManager);
  584. serviceCollection.AddSingleton(TaskManager);
  585. serviceCollection.AddSingleton(XmlSerializer);
  586. ProcessFactory = new ProcessFactory();
  587. serviceCollection.AddSingleton(ProcessFactory);
  588. ApplicationHost.StreamHelper = new StreamHelper();
  589. serviceCollection.AddSingleton(StreamHelper);
  590. serviceCollection.AddSingleton(typeof(ICryptoProvider), typeof(CryptographyProvider));
  591. SocketFactory = new SocketFactory();
  592. serviceCollection.AddSingleton(SocketFactory);
  593. serviceCollection.AddSingleton(typeof(IInstallationManager), typeof(InstallationManager));
  594. ZipClient = new ZipClient();
  595. serviceCollection.AddSingleton(ZipClient);
  596. HttpResultFactory = new HttpResultFactory(LoggerFactory, FileSystemManager, JsonSerializer, StreamHelper);
  597. serviceCollection.AddSingleton(HttpResultFactory);
  598. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  599. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  600. serviceCollection.AddSingleton(ServerConfigurationManager);
  601. LocalizationManager = new LocalizationManager(ServerConfigurationManager, JsonSerializer, LoggerFactory);
  602. await LocalizationManager.LoadAll().ConfigureAwait(false);
  603. serviceCollection.AddSingleton<ILocalizationManager>(LocalizationManager);
  604. serviceCollection.AddSingleton<IBlurayExaminer>(new BdInfoExaminer(FileSystemManager));
  605. UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
  606. serviceCollection.AddSingleton(UserDataManager);
  607. var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory, JsonSerializer, ApplicationPaths, FileSystemManager);
  608. serviceCollection.AddSingleton<IDisplayPreferencesRepository>(displayPreferencesRepo);
  609. ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory, LocalizationManager);
  610. serviceCollection.AddSingleton<IItemRepository>(ItemRepository);
  611. AuthenticationRepository = GetAuthenticationRepository();
  612. serviceCollection.AddSingleton(AuthenticationRepository);
  613. UserRepository = GetUserRepository();
  614. UserManager = new UserManager(LoggerFactory, ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager);
  615. serviceCollection.AddSingleton(UserManager);
  616. LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
  617. serviceCollection.AddSingleton(LibraryManager);
  618. // TODO wtaylor: investigate use of second music manager
  619. var musicManager = new MusicManager(LibraryManager);
  620. serviceCollection.AddSingleton<IMusicManager>(new MusicManager(LibraryManager));
  621. LibraryMonitor = new LibraryMonitor(LoggerFactory, LibraryManager, ServerConfigurationManager, FileSystemManager);
  622. serviceCollection.AddSingleton(LibraryMonitor);
  623. serviceCollection.AddSingleton<ISearchEngine>(new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  624. CertificateInfo = GetCertificateInfo(true);
  625. Certificate = GetCertificate(CertificateInfo);
  626. HttpServer = new HttpListenerHost(
  627. this,
  628. LoggerFactory.CreateLogger<HttpListenerHost>(),
  629. ServerConfigurationManager,
  630. _configuration,
  631. NetworkManager,
  632. JsonSerializer,
  633. XmlSerializer,
  634. CreateHttpListener())
  635. {
  636. GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading")
  637. };
  638. serviceCollection.AddSingleton(HttpServer);
  639. ImageProcessor = GetImageProcessor();
  640. serviceCollection.AddSingleton(ImageProcessor);
  641. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  642. serviceCollection.AddSingleton(TVSeriesManager);
  643. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager);
  644. serviceCollection.AddSingleton(DeviceManager);
  645. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
  646. serviceCollection.AddSingleton(MediaSourceManager);
  647. SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
  648. serviceCollection.AddSingleton(SubtitleManager);
  649. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  650. serviceCollection.AddSingleton(ProviderManager);
  651. DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ProviderManager, this, () => MediaSourceManager, () => LiveTvManager);
  652. serviceCollection.AddSingleton(DtoService);
  653. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, ProviderManager);
  654. serviceCollection.AddSingleton(ChannelManager);
  655. SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, this, AuthenticationRepository, DeviceManager, MediaSourceManager);
  656. serviceCollection.AddSingleton(SessionManager);
  657. serviceCollection.AddSingleton<IDlnaManager>(
  658. new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this));
  659. CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
  660. serviceCollection.AddSingleton(CollectionManager);
  661. PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory, UserManager, ProviderManager);
  662. serviceCollection.AddSingleton(PlaylistManager);
  663. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
  664. serviceCollection.AddSingleton(LiveTvManager);
  665. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  666. serviceCollection.AddSingleton(UserViewManager);
  667. NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager);
  668. serviceCollection.AddSingleton(NotificationManager);
  669. serviceCollection.AddSingleton<IDeviceDiscovery>(
  670. new DeviceDiscovery(LoggerFactory, ServerConfigurationManager, SocketFactory));
  671. ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository);
  672. serviceCollection.AddSingleton(ChapterManager);
  673. MediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  674. LoggerFactory,
  675. JsonSerializer,
  676. StartupOptions.FFmpegPath,
  677. ServerConfigurationManager,
  678. FileSystemManager,
  679. () => SubtitleEncoder,
  680. () => MediaSourceManager,
  681. ProcessFactory,
  682. 5000,
  683. LocalizationManager);
  684. serviceCollection.AddSingleton(MediaEncoder);
  685. EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager);
  686. serviceCollection.AddSingleton(EncodingManager);
  687. var activityLogRepo = GetActivityLogRepository();
  688. serviceCollection.AddSingleton(activityLogRepo);
  689. serviceCollection.AddSingleton<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager));
  690. var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
  691. serviceCollection.AddSingleton<IAuthorizationContext>(authContext);
  692. serviceCollection.AddSingleton<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  693. AuthService = new AuthService(authContext, ServerConfigurationManager, SessionManager, NetworkManager);
  694. serviceCollection.AddSingleton(AuthService);
  695. SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory);
  696. serviceCollection.AddSingleton(SubtitleEncoder);
  697. serviceCollection.AddSingleton(typeof(IResourceFileManager), typeof(ResourceFileManager));
  698. displayPreferencesRepo.Initialize();
  699. var userDataRepo = new SqliteUserDataRepository(LoggerFactory, ApplicationPaths);
  700. SetStaticProperties();
  701. ((UserManager)UserManager).Initialize();
  702. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  703. ItemRepository.Initialize(userDataRepo, UserManager);
  704. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  705. _serviceProvider = serviceCollection.BuildServiceProvider();
  706. }
  707. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  708. {
  709. // Distinct these to prevent users from reporting problems that aren't actually problems
  710. var commandLineArgs = Environment
  711. .GetCommandLineArgs()
  712. .Distinct();
  713. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  714. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  715. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  716. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  717. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  718. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  719. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  720. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  721. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  722. }
  723. private X509Certificate2 GetCertificate(CertificateInfo info)
  724. {
  725. var certificateLocation = info?.Path;
  726. if (string.IsNullOrWhiteSpace(certificateLocation))
  727. {
  728. return null;
  729. }
  730. try
  731. {
  732. if (!File.Exists(certificateLocation))
  733. {
  734. return null;
  735. }
  736. // Don't use an empty string password
  737. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  738. var localCert = new X509Certificate2(certificateLocation, password);
  739. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  740. if (!localCert.HasPrivateKey)
  741. {
  742. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  743. return null;
  744. }
  745. return localCert;
  746. }
  747. catch (Exception ex)
  748. {
  749. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  750. return null;
  751. }
  752. }
  753. private IImageProcessor GetImageProcessor()
  754. {
  755. return new ImageProcessor(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
  756. }
  757. /// <summary>
  758. /// Gets the user repository.
  759. /// </summary>
  760. /// <returns>Task{IUserRepository}.</returns>
  761. private IUserRepository GetUserRepository()
  762. {
  763. var repo = new SqliteUserRepository(LoggerFactory, ApplicationPaths, 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.AddParts(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. LogErrors = false,
  1226. LogRequest = false,
  1227. BufferContent = false,
  1228. CancellationToken = cancellationToken
  1229. }).ConfigureAwait(false))
  1230. {
  1231. string res = await response.ReadToEndAsync().ConfigureAwait(false);
  1232. return GetWanApiUrl(res.Trim());
  1233. }
  1234. }
  1235. catch (Exception ex)
  1236. {
  1237. Logger.LogError(ex, "Error getting WAN Ip address information");
  1238. }
  1239. return null;
  1240. }
  1241. /// <summary>
  1242. /// Removes the scope id from IPv6 addresses.
  1243. /// </summary>
  1244. /// <param name="address">The IPv6 address.</param>
  1245. /// <returns>The IPv6 address without the scope id.</returns>
  1246. private string RemoveScopeId(string address)
  1247. {
  1248. var index = address.IndexOf('%');
  1249. if (index == -1)
  1250. {
  1251. return address;
  1252. }
  1253. return address.Substring(0, index);
  1254. }
  1255. public string GetLocalApiUrl(IPAddress ipAddress)
  1256. {
  1257. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1258. {
  1259. var str = RemoveScopeId(ipAddress.ToString());
  1260. return GetLocalApiUrl("[" + str + "]");
  1261. }
  1262. return GetLocalApiUrl(ipAddress.ToString());
  1263. }
  1264. public string GetLocalApiUrl(string host)
  1265. {
  1266. if (EnableHttps)
  1267. {
  1268. return string.Format("https://{0}:{1}",
  1269. host,
  1270. HttpsPort.ToString(CultureInfo.InvariantCulture));
  1271. }
  1272. return string.Format("http://{0}:{1}",
  1273. host,
  1274. HttpPort.ToString(CultureInfo.InvariantCulture));
  1275. }
  1276. public string GetWanApiUrl(IPAddress ipAddress)
  1277. {
  1278. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1279. {
  1280. var str = RemoveScopeId(ipAddress.ToString());
  1281. return GetWanApiUrl("[" + str + "]");
  1282. }
  1283. return GetWanApiUrl(ipAddress.ToString());
  1284. }
  1285. public string GetWanApiUrl(string host)
  1286. {
  1287. if (EnableHttps)
  1288. {
  1289. return string.Format("https://{0}:{1}",
  1290. host,
  1291. ServerConfigurationManager.Configuration.PublicHttpsPort.ToString(CultureInfo.InvariantCulture));
  1292. }
  1293. return string.Format("http://{0}:{1}",
  1294. host,
  1295. ServerConfigurationManager.Configuration.PublicPort.ToString(CultureInfo.InvariantCulture));
  1296. }
  1297. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1298. {
  1299. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1300. }
  1301. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1302. {
  1303. var addresses = ServerConfigurationManager
  1304. .Configuration
  1305. .LocalNetworkAddresses
  1306. .Select(NormalizeConfiguredLocalAddress)
  1307. .Where(i => i != null)
  1308. .ToList();
  1309. if (addresses.Count == 0)
  1310. {
  1311. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1312. }
  1313. var resultList = new List<IPAddress>();
  1314. foreach (var address in addresses)
  1315. {
  1316. if (!allowLoopback)
  1317. {
  1318. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1319. {
  1320. continue;
  1321. }
  1322. }
  1323. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1324. if (valid)
  1325. {
  1326. resultList.Add(address);
  1327. if (limit > 0 && resultList.Count >= limit)
  1328. {
  1329. return resultList;
  1330. }
  1331. }
  1332. }
  1333. return resultList;
  1334. }
  1335. private IPAddress NormalizeConfiguredLocalAddress(string address)
  1336. {
  1337. var index = address.Trim('/').IndexOf('/');
  1338. if (index != -1)
  1339. {
  1340. address = address.Substring(index + 1);
  1341. }
  1342. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1343. {
  1344. return result;
  1345. }
  1346. return null;
  1347. }
  1348. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1349. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1350. {
  1351. if (address.Equals(IPAddress.Loopback) ||
  1352. address.Equals(IPAddress.IPv6Loopback))
  1353. {
  1354. return true;
  1355. }
  1356. var apiUrl = GetLocalApiUrl(address);
  1357. apiUrl += "/system/ping";
  1358. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1359. {
  1360. return cachedResult;
  1361. }
  1362. #if DEBUG
  1363. const bool LogPing = true;
  1364. #else
  1365. const bool LogPing = false;
  1366. #endif
  1367. try
  1368. {
  1369. using (var response = await HttpClient.SendAsync(
  1370. new HttpRequestOptions
  1371. {
  1372. Url = apiUrl,
  1373. LogErrorResponseBody = false,
  1374. LogErrors = LogPing,
  1375. LogRequest = LogPing,
  1376. BufferContent = false,
  1377. CancellationToken = cancellationToken
  1378. }, HttpMethod.Post).ConfigureAwait(false))
  1379. {
  1380. using (var reader = new StreamReader(response.Content))
  1381. {
  1382. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1383. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1384. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1385. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1386. return valid;
  1387. }
  1388. }
  1389. }
  1390. catch (OperationCanceledException)
  1391. {
  1392. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1393. throw;
  1394. }
  1395. catch (Exception ex)
  1396. {
  1397. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1398. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1399. return false;
  1400. }
  1401. }
  1402. public string FriendlyName =>
  1403. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1404. ? Environment.MachineName
  1405. : ServerConfigurationManager.Configuration.ServerName;
  1406. public int HttpPort { get; private set; }
  1407. public int HttpsPort { get; private set; }
  1408. /// <summary>
  1409. /// Shuts down.
  1410. /// </summary>
  1411. public async Task Shutdown()
  1412. {
  1413. if (IsShuttingDown)
  1414. {
  1415. return;
  1416. }
  1417. IsShuttingDown = true;
  1418. try
  1419. {
  1420. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1421. }
  1422. catch (Exception ex)
  1423. {
  1424. Logger.LogError(ex, "Error sending server shutdown notification");
  1425. }
  1426. ShutdownInternal();
  1427. }
  1428. protected abstract void ShutdownInternal();
  1429. public event EventHandler HasUpdateAvailableChanged;
  1430. private bool _hasUpdateAvailable;
  1431. public bool HasUpdateAvailable
  1432. {
  1433. get => _hasUpdateAvailable;
  1434. set
  1435. {
  1436. var fireEvent = value && !_hasUpdateAvailable;
  1437. _hasUpdateAvailable = value;
  1438. if (fireEvent)
  1439. {
  1440. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1441. }
  1442. }
  1443. }
  1444. /// <summary>
  1445. /// Removes the plugin.
  1446. /// </summary>
  1447. /// <param name="plugin">The plugin.</param>
  1448. public void RemovePlugin(IPlugin plugin)
  1449. {
  1450. var list = Plugins.ToList();
  1451. list.Remove(plugin);
  1452. Plugins = list.ToArray();
  1453. }
  1454. /// <summary>
  1455. /// This returns localhost in the case of no external dns, and the hostname if the
  1456. /// dns is prefixed with a valid Uri prefix.
  1457. /// </summary>
  1458. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  1459. /// <returns>The hostname in <paramref name="externalDns"/></returns>
  1460. private static string GetHostnameFromExternalDns(string externalDns)
  1461. {
  1462. if (string.IsNullOrEmpty(externalDns))
  1463. {
  1464. return "localhost";
  1465. }
  1466. try
  1467. {
  1468. return new Uri(externalDns).Host;
  1469. }
  1470. catch
  1471. {
  1472. return externalDns;
  1473. }
  1474. }
  1475. public virtual void LaunchUrl(string url)
  1476. {
  1477. if (!CanLaunchWebBrowser)
  1478. {
  1479. throw new NotSupportedException();
  1480. }
  1481. var process = ProcessFactory.Create(new ProcessOptions
  1482. {
  1483. FileName = url,
  1484. EnableRaisingEvents = true,
  1485. UseShellExecute = true,
  1486. ErrorDialog = false
  1487. });
  1488. process.Exited += ProcessExited;
  1489. try
  1490. {
  1491. process.Start();
  1492. }
  1493. catch (Exception ex)
  1494. {
  1495. Logger.LogError(ex, "Error launching url: {url}", url);
  1496. throw;
  1497. }
  1498. }
  1499. private static void ProcessExited(object sender, EventArgs e)
  1500. {
  1501. ((IProcess)sender).Dispose();
  1502. }
  1503. public virtual void EnableLoopback(string appName)
  1504. {
  1505. }
  1506. private bool _disposed = false;
  1507. /// <summary>
  1508. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1509. /// </summary>
  1510. public void Dispose()
  1511. {
  1512. Dispose(true);
  1513. GC.SuppressFinalize(this);
  1514. }
  1515. /// <summary>
  1516. /// Releases unmanaged and - optionally - managed resources.
  1517. /// </summary>
  1518. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1519. protected virtual void Dispose(bool dispose)
  1520. {
  1521. if (_disposed)
  1522. {
  1523. return;
  1524. }
  1525. if (dispose)
  1526. {
  1527. var type = GetType();
  1528. Logger.LogInformation("Disposing {Type}", type.Name);
  1529. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1530. _disposableParts.Clear();
  1531. foreach (var part in parts)
  1532. {
  1533. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1534. try
  1535. {
  1536. part.Dispose();
  1537. }
  1538. catch (Exception ex)
  1539. {
  1540. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1541. }
  1542. }
  1543. UserRepository.Dispose();
  1544. }
  1545. UserRepository = null;
  1546. _disposed = true;
  1547. }
  1548. }
  1549. internal class CertificateInfo
  1550. {
  1551. public string Path { get; set; }
  1552. public string Password { get; set; }
  1553. }
  1554. }