ApplicationHost.cs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Reflection;
  11. using System.Runtime.InteropServices;
  12. using System.Security.Cryptography.X509Certificates;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using Emby.Dlna;
  16. using Emby.Dlna.Main;
  17. using Emby.Dlna.Ssdp;
  18. using Emby.Drawing;
  19. using Emby.Notifications;
  20. using Emby.Photos;
  21. using Emby.Server.Implementations.Archiving;
  22. using Emby.Server.Implementations.Channels;
  23. using Emby.Server.Implementations.Collections;
  24. using Emby.Server.Implementations.Configuration;
  25. using Emby.Server.Implementations.Cryptography;
  26. using Emby.Server.Implementations.Data;
  27. using Emby.Server.Implementations.Devices;
  28. using Emby.Server.Implementations.Dto;
  29. using Emby.Server.Implementations.HttpServer.Security;
  30. using Emby.Server.Implementations.IO;
  31. using Emby.Server.Implementations.Library;
  32. using Emby.Server.Implementations.LiveTv;
  33. using Emby.Server.Implementations.Localization;
  34. using Emby.Server.Implementations.Net;
  35. using Emby.Server.Implementations.Playlists;
  36. using Emby.Server.Implementations.Plugins;
  37. using Emby.Server.Implementations.QuickConnect;
  38. using Emby.Server.Implementations.ScheduledTasks;
  39. using Emby.Server.Implementations.Security;
  40. using Emby.Server.Implementations.Serialization;
  41. using Emby.Server.Implementations.Session;
  42. using Emby.Server.Implementations.SyncPlay;
  43. using Emby.Server.Implementations.TV;
  44. using Emby.Server.Implementations.Udp;
  45. using Emby.Server.Implementations.Updates;
  46. using Jellyfin.Api.Helpers;
  47. using Jellyfin.Networking.Configuration;
  48. using Jellyfin.Networking.Manager;
  49. using MediaBrowser.Common;
  50. using MediaBrowser.Common.Configuration;
  51. using MediaBrowser.Common.Events;
  52. using MediaBrowser.Common.Net;
  53. using MediaBrowser.Common.Plugins;
  54. using MediaBrowser.Common.Updates;
  55. using MediaBrowser.Controller;
  56. using MediaBrowser.Controller.Channels;
  57. using MediaBrowser.Controller.Chapters;
  58. using MediaBrowser.Controller.Collections;
  59. using MediaBrowser.Controller.Configuration;
  60. using MediaBrowser.Controller.Devices;
  61. using MediaBrowser.Controller.Dlna;
  62. using MediaBrowser.Controller.Drawing;
  63. using MediaBrowser.Controller.Dto;
  64. using MediaBrowser.Controller.Entities;
  65. using MediaBrowser.Controller.Library;
  66. using MediaBrowser.Controller.LiveTv;
  67. using MediaBrowser.Controller.MediaEncoding;
  68. using MediaBrowser.Controller.Net;
  69. using MediaBrowser.Controller.Notifications;
  70. using MediaBrowser.Controller.Persistence;
  71. using MediaBrowser.Controller.Playlists;
  72. using MediaBrowser.Controller.Plugins;
  73. using MediaBrowser.Controller.Providers;
  74. using MediaBrowser.Controller.QuickConnect;
  75. using MediaBrowser.Controller.Resolvers;
  76. using MediaBrowser.Controller.Security;
  77. using MediaBrowser.Controller.Session;
  78. using MediaBrowser.Controller.Sorting;
  79. using MediaBrowser.Controller.Subtitles;
  80. using MediaBrowser.Controller.SyncPlay;
  81. using MediaBrowser.Controller.TV;
  82. using MediaBrowser.LocalMetadata.Savers;
  83. using MediaBrowser.MediaEncoding.BdInfo;
  84. using MediaBrowser.Model.Cryptography;
  85. using MediaBrowser.Model.Dlna;
  86. using MediaBrowser.Model.Globalization;
  87. using MediaBrowser.Model.IO;
  88. using MediaBrowser.Model.MediaInfo;
  89. using MediaBrowser.Model.Net;
  90. using MediaBrowser.Model.Serialization;
  91. using MediaBrowser.Model.System;
  92. using MediaBrowser.Model.Tasks;
  93. using MediaBrowser.Providers.Chapters;
  94. using MediaBrowser.Providers.Manager;
  95. using MediaBrowser.Providers.Plugins.Tmdb;
  96. using MediaBrowser.Providers.Subtitles;
  97. using MediaBrowser.XbmcMetadata.Providers;
  98. using Microsoft.AspNetCore.Http;
  99. using Microsoft.AspNetCore.Mvc;
  100. using Microsoft.Extensions.Configuration;
  101. using Microsoft.Extensions.DependencyInjection;
  102. using Microsoft.Extensions.Logging;
  103. using Prometheus.DotNetRuntime;
  104. using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
  105. namespace Emby.Server.Implementations
  106. {
  107. /// <summary>
  108. /// Class CompositionRoot.
  109. /// </summary>
  110. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  111. {
  112. /// <summary>
  113. /// The environment variable prefixes to log at server startup.
  114. /// </summary>
  115. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  116. private readonly IFileSystem _fileSystemManager;
  117. private readonly IConfiguration _startupConfig;
  118. private readonly IXmlSerializer _xmlSerializer;
  119. private readonly IStartupOptions _startupOptions;
  120. private readonly IPluginManager _pluginManager;
  121. private List<Type> _creatingInstances;
  122. private IMediaEncoder _mediaEncoder;
  123. private ISessionManager _sessionManager;
  124. private string[] _urlPrefixes;
  125. /// <summary>
  126. /// Gets a value indicating whether this instance can self restart.
  127. /// </summary>
  128. public bool CanSelfRestart => _startupOptions.RestartPath != null;
  129. public bool CoreStartupHasCompleted { get; private set; }
  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. return OperatingSystem.IsWindows() || OperatingSystem.IsMacOS();
  143. }
  144. }
  145. /// <summary>
  146. /// Gets the <see cref="INetworkManager"/> singleton instance.
  147. /// </summary>
  148. public INetworkManager NetManager { get; internal set; }
  149. /// <summary>
  150. /// Occurs when [has pending restart changed].
  151. /// </summary>
  152. public event EventHandler HasPendingRestartChanged;
  153. /// <summary>
  154. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  155. /// </summary>
  156. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  157. public bool HasPendingRestart { get; private set; }
  158. /// <inheritdoc />
  159. public bool IsShuttingDown { get; private set; }
  160. /// <summary>
  161. /// Gets the logger.
  162. /// </summary>
  163. protected ILogger<ApplicationHost> Logger { get; }
  164. protected IServiceCollection ServiceCollection { get; }
  165. /// <summary>
  166. /// Gets the logger factory.
  167. /// </summary>
  168. protected ILoggerFactory LoggerFactory { get; }
  169. /// <summary>
  170. /// Gets or sets the application paths.
  171. /// </summary>
  172. /// <value>The application paths.</value>
  173. protected IServerApplicationPaths ApplicationPaths { get; set; }
  174. /// <summary>
  175. /// Gets or sets all concrete types.
  176. /// </summary>
  177. /// <value>All concrete types.</value>
  178. private Type[] _allConcreteTypes;
  179. /// <summary>
  180. /// The disposable parts.
  181. /// </summary>
  182. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  183. /// <summary>
  184. /// Gets or sets the configuration manager.
  185. /// </summary>
  186. /// <value>The configuration manager.</value>
  187. public ServerConfigurationManager ConfigurationManager { get; set; }
  188. /// <summary>
  189. /// Gets or sets the service provider.
  190. /// </summary>
  191. public IServiceProvider ServiceProvider { get; set; }
  192. /// <summary>
  193. /// Gets the http port for the webhost.
  194. /// </summary>
  195. public int HttpPort { get; private set; }
  196. /// <summary>
  197. /// Gets the https port for the webhost.
  198. /// </summary>
  199. public int HttpsPort { get; private set; }
  200. /// <summary>
  201. /// Gets the value of the PublishedServerUrl setting.
  202. /// </summary>
  203. public string PublishedServerUrl => _startupOptions.PublishedServerUrl ?? _startupConfig[UdpServer.AddressOverrideConfigKey];
  204. /// <summary>
  205. /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
  206. /// </summary>
  207. /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
  208. /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
  209. /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
  210. /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param>
  211. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  212. /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
  213. public ApplicationHost(
  214. IServerApplicationPaths applicationPaths,
  215. ILoggerFactory loggerFactory,
  216. IStartupOptions options,
  217. IConfiguration startupConfig,
  218. IFileSystem fileSystem,
  219. IServiceCollection serviceCollection)
  220. {
  221. ApplicationPaths = applicationPaths;
  222. LoggerFactory = loggerFactory;
  223. _startupOptions = options;
  224. _startupConfig = startupConfig;
  225. _fileSystemManager = fileSystem;
  226. ServiceCollection = serviceCollection;
  227. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  228. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  229. ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
  230. ApplicationVersionString = ApplicationVersion.ToString(3);
  231. ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  232. _xmlSerializer = new MyXmlSerializer();
  233. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
  234. _pluginManager = new PluginManager(
  235. LoggerFactory.CreateLogger<PluginManager>(),
  236. this,
  237. ConfigurationManager.Configuration,
  238. ApplicationPaths.PluginsPath,
  239. ApplicationVersion);
  240. }
  241. /// <summary>
  242. /// Temporary function to migration network settings out of system.xml and into network.xml.
  243. /// TODO: remove at the point when a fixed migration path has been decided upon.
  244. /// </summary>
  245. private void MigrateNetworkConfiguration()
  246. {
  247. string path = Path.Combine(ConfigurationManager.CommonApplicationPaths.ConfigurationDirectoryPath, "network.xml");
  248. if (!File.Exists(path))
  249. {
  250. var networkSettings = new NetworkConfiguration();
  251. ClassMigrationHelper.CopyProperties(ConfigurationManager.Configuration, networkSettings);
  252. _xmlSerializer.SerializeToFile(networkSettings, path);
  253. Logger.LogDebug("Successfully migrated network settings.");
  254. }
  255. }
  256. public string ExpandVirtualPath(string path)
  257. {
  258. var appPaths = ApplicationPaths;
  259. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  260. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  261. }
  262. public string ReverseVirtualPath(string path)
  263. {
  264. var appPaths = ApplicationPaths;
  265. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  266. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  267. }
  268. /// <inheritdoc />
  269. public Version ApplicationVersion { get; }
  270. /// <inheritdoc />
  271. public string ApplicationVersionString { get; }
  272. /// <summary>
  273. /// Gets the current application user agent.
  274. /// </summary>
  275. /// <value>The application user agent.</value>
  276. public string ApplicationUserAgent { get; }
  277. /// <summary>
  278. /// Gets the email address for use within a comment section of a user agent field.
  279. /// Presently used to provide contact information to MusicBrainz service.
  280. /// </summary>
  281. public string ApplicationUserAgentAddress => "team@jellyfin.org";
  282. /// <summary>
  283. /// Gets the current application name.
  284. /// </summary>
  285. /// <value>The application name.</value>
  286. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  287. private DeviceId _deviceId;
  288. public string SystemId
  289. {
  290. get
  291. {
  292. _deviceId ??= new DeviceId(ApplicationPaths, LoggerFactory);
  293. return _deviceId.Value;
  294. }
  295. }
  296. /// <inheritdoc/>
  297. public string Name => ApplicationProductName;
  298. /// <summary>
  299. /// Creates an instance of type and resolves all constructor dependencies.
  300. /// </summary>
  301. /// <param name="type">The type.</param>
  302. /// <returns>System.Object.</returns>
  303. public object CreateInstance(Type type)
  304. => ActivatorUtilities.CreateInstance(ServiceProvider, type);
  305. /// <summary>
  306. /// Creates an instance of type and resolves all constructor dependencies.
  307. /// </summary>
  308. /// <typeparam name="T">The type.</typeparam>
  309. /// <returns>T.</returns>
  310. public T CreateInstance<T>()
  311. => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
  312. /// <summary>
  313. /// Creates the instance safe.
  314. /// </summary>
  315. /// <param name="type">The type.</param>
  316. /// <returns>System.Object.</returns>
  317. protected object CreateInstanceSafe(Type type)
  318. {
  319. _creatingInstances ??= new List<Type>();
  320. if (_creatingInstances.IndexOf(type) != -1)
  321. {
  322. Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
  323. foreach (var entry in _creatingInstances)
  324. {
  325. Logger.LogError("Called from: {TypeName}", entry.FullName);
  326. }
  327. _pluginManager.FailPlugin(type.Assembly);
  328. throw new ExternalException("DI Loop detected.");
  329. }
  330. try
  331. {
  332. _creatingInstances.Add(type);
  333. Logger.LogDebug("Creating instance of {Type}", type);
  334. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  335. }
  336. catch (Exception ex)
  337. {
  338. Logger.LogError(ex, "Error creating {Type}", type);
  339. // If this is a plugin fail it.
  340. _pluginManager.FailPlugin(type.Assembly);
  341. return null;
  342. }
  343. finally
  344. {
  345. _creatingInstances.Remove(type);
  346. }
  347. }
  348. /// <summary>
  349. /// Resolves this instance.
  350. /// </summary>
  351. /// <typeparam name="T">The type.</typeparam>
  352. /// <returns>``0.</returns>
  353. public T Resolve<T>() => ServiceProvider.GetService<T>();
  354. /// <inheritdoc/>
  355. public IEnumerable<Type> GetExportTypes<T>()
  356. {
  357. var currentType = typeof(T);
  358. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  359. }
  360. /// <inheritdoc />
  361. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  362. {
  363. // Convert to list so this isn't executed for each iteration
  364. var parts = GetExportTypes<T>()
  365. .Select(CreateInstanceSafe)
  366. .Where(i => i != null)
  367. .Cast<T>()
  368. .ToList();
  369. if (manageLifetime)
  370. {
  371. lock (_disposableParts)
  372. {
  373. _disposableParts.AddRange(parts.OfType<IDisposable>());
  374. }
  375. }
  376. return parts;
  377. }
  378. /// <inheritdoc />
  379. public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
  380. {
  381. // Convert to list so this isn't executed for each iteration
  382. var parts = GetExportTypes<T>()
  383. .Select(i => defaultFunc(i))
  384. .Where(i => i != null)
  385. .Cast<T>()
  386. .ToList();
  387. if (manageLifetime)
  388. {
  389. lock (_disposableParts)
  390. {
  391. _disposableParts.AddRange(parts.OfType<IDisposable>());
  392. }
  393. }
  394. return parts;
  395. }
  396. /// <summary>
  397. /// Runs the startup tasks.
  398. /// </summary>
  399. /// <param name="cancellationToken">The cancellation token.</param>
  400. /// <returns><see cref="Task" />.</returns>
  401. public async Task RunStartupTasksAsync(CancellationToken cancellationToken)
  402. {
  403. cancellationToken.ThrowIfCancellationRequested();
  404. Logger.LogInformation("Running startup tasks");
  405. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  406. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  407. ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
  408. _mediaEncoder.SetFFmpegPath();
  409. Logger.LogInformation("ServerId: {ServerId}", SystemId);
  410. var entryPoints = GetExports<IServerEntryPoint>();
  411. cancellationToken.ThrowIfCancellationRequested();
  412. var stopWatch = new Stopwatch();
  413. stopWatch.Start();
  414. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  415. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  416. Logger.LogInformation("Core startup complete");
  417. CoreStartupHasCompleted = true;
  418. cancellationToken.ThrowIfCancellationRequested();
  419. stopWatch.Restart();
  420. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  421. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  422. stopWatch.Stop();
  423. }
  424. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  425. {
  426. foreach (var entryPoint in entryPoints)
  427. {
  428. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  429. {
  430. continue;
  431. }
  432. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  433. yield return entryPoint.RunAsync();
  434. }
  435. }
  436. /// <inheritdoc/>
  437. public void Init()
  438. {
  439. DiscoverTypes();
  440. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  441. // Have to migrate settings here as migration subsystem not yet initialised.
  442. MigrateNetworkConfiguration();
  443. NetManager = new NetworkManager(ConfigurationManager, LoggerFactory.CreateLogger<NetworkManager>());
  444. // Initialize runtime stat collection
  445. if (ConfigurationManager.Configuration.EnableMetrics)
  446. {
  447. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  448. }
  449. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  450. HttpPort = networkConfiguration.HttpServerPortNumber;
  451. HttpsPort = networkConfiguration.HttpsPortNumber;
  452. // Safeguard against invalid configuration
  453. if (HttpPort == HttpsPort)
  454. {
  455. HttpPort = NetworkConfiguration.DefaultHttpPort;
  456. HttpsPort = NetworkConfiguration.DefaultHttpsPort;
  457. }
  458. CertificateInfo = new CertificateInfo
  459. {
  460. Path = networkConfiguration.CertificatePath,
  461. Password = networkConfiguration.CertificatePassword
  462. };
  463. Certificate = GetCertificate(CertificateInfo);
  464. RegisterServices();
  465. _pluginManager.RegisterServices(ServiceCollection);
  466. }
  467. /// <summary>
  468. /// Registers services/resources with the service collection that will be available via DI.
  469. /// </summary>
  470. protected virtual void RegisterServices()
  471. {
  472. ServiceCollection.AddSingleton(_startupOptions);
  473. ServiceCollection.AddMemoryCache();
  474. ServiceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
  475. ServiceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
  476. ServiceCollection.AddSingleton<IApplicationHost>(this);
  477. ServiceCollection.AddSingleton<IPluginManager>(_pluginManager);
  478. ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  479. ServiceCollection.AddSingleton(_fileSystemManager);
  480. ServiceCollection.AddSingleton<TmdbClientManager>();
  481. ServiceCollection.AddSingleton(NetManager);
  482. ServiceCollection.AddSingleton<ITaskManager, TaskManager>();
  483. ServiceCollection.AddSingleton(_xmlSerializer);
  484. ServiceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  485. ServiceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  486. ServiceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  487. ServiceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  488. ServiceCollection.AddSingleton<IZipClient, ZipClient>();
  489. ServiceCollection.AddSingleton<IServerApplicationHost>(this);
  490. ServiceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  491. ServiceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  492. ServiceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  493. ServiceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  494. ServiceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  495. ServiceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  496. ServiceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  497. ServiceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  498. ServiceCollection.AddSingleton<EncodingHelper>();
  499. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  500. ServiceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  501. ServiceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  502. ServiceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  503. ServiceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  504. ServiceCollection.AddSingleton<IMusicManager, MusicManager>();
  505. ServiceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  506. ServiceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  507. ServiceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  508. ServiceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  509. ServiceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  510. ServiceCollection.AddSingleton<IDeviceManager, DeviceManager>();
  511. ServiceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  512. ServiceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  513. ServiceCollection.AddSingleton<IProviderManager, ProviderManager>();
  514. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  515. ServiceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  516. ServiceCollection.AddSingleton<IDtoService, DtoService>();
  517. ServiceCollection.AddSingleton<IChannelManager, ChannelManager>();
  518. ServiceCollection.AddSingleton<ISessionManager, SessionManager>();
  519. ServiceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  520. ServiceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  521. ServiceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  522. ServiceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  523. ServiceCollection.AddSingleton<LiveTvDtoService>();
  524. ServiceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  525. ServiceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  526. ServiceCollection.AddSingleton<INotificationManager, NotificationManager>();
  527. ServiceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  528. ServiceCollection.AddSingleton<IChapterManager, ChapterManager>();
  529. ServiceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  530. ServiceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  531. ServiceCollection.AddSingleton<ISessionContext, SessionContext>();
  532. ServiceCollection.AddSingleton<IAuthService, AuthService>();
  533. ServiceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  534. ServiceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  535. ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  536. ServiceCollection.AddSingleton<TranscodingJobHelper>();
  537. ServiceCollection.AddScoped<MediaInfoHelper>();
  538. ServiceCollection.AddScoped<AudioHelper>();
  539. ServiceCollection.AddScoped<DynamicHlsHelper>();
  540. ServiceCollection.AddSingleton<IDirectoryService, DirectoryService>();
  541. }
  542. /// <summary>
  543. /// Create services registered with the service container that need to be initialized at application startup.
  544. /// </summary>
  545. /// <returns>A task representing the service initialization operation.</returns>
  546. public async Task InitializeServices()
  547. {
  548. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  549. await localizationManager.LoadAll().ConfigureAwait(false);
  550. _mediaEncoder = Resolve<IMediaEncoder>();
  551. _sessionManager = Resolve<ISessionManager>();
  552. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  553. SetStaticProperties();
  554. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  555. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  556. FindParts();
  557. }
  558. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  559. {
  560. // Distinct these to prevent users from reporting problems that aren't actually problems
  561. var commandLineArgs = Environment
  562. .GetCommandLineArgs()
  563. .Distinct();
  564. // Get all relevant environment variables
  565. var allEnvVars = Environment.GetEnvironmentVariables();
  566. var relevantEnvVars = new Dictionary<object, object>();
  567. foreach (var key in allEnvVars.Keys)
  568. {
  569. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  570. {
  571. relevantEnvVars.Add(key, allEnvVars[key]);
  572. }
  573. }
  574. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  575. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  576. logger.LogInformation("Operating system: {OS}", MediaBrowser.Common.System.OperatingSystem.Name);
  577. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  578. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  579. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  580. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  581. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  582. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  583. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  584. }
  585. private X509Certificate2 GetCertificate(CertificateInfo info)
  586. {
  587. var certificateLocation = info?.Path;
  588. if (string.IsNullOrWhiteSpace(certificateLocation))
  589. {
  590. return null;
  591. }
  592. try
  593. {
  594. if (!File.Exists(certificateLocation))
  595. {
  596. return null;
  597. }
  598. // Don't use an empty string password
  599. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  600. var localCert = new X509Certificate2(certificateLocation, password, X509KeyStorageFlags.UserKeySet);
  601. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  602. if (!localCert.HasPrivateKey)
  603. {
  604. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  605. return null;
  606. }
  607. return localCert;
  608. }
  609. catch (Exception ex)
  610. {
  611. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  612. return null;
  613. }
  614. }
  615. /// <summary>
  616. /// Dirty hacks.
  617. /// </summary>
  618. private void SetStaticProperties()
  619. {
  620. // For now there's no real way to inject these properly
  621. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  622. BaseItem.ConfigurationManager = ConfigurationManager;
  623. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  624. BaseItem.ProviderManager = Resolve<IProviderManager>();
  625. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  626. BaseItem.ItemRepository = Resolve<IItemRepository>();
  627. BaseItem.FileSystem = _fileSystemManager;
  628. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  629. BaseItem.ChannelManager = Resolve<IChannelManager>();
  630. Video.LiveTvManager = Resolve<ILiveTvManager>();
  631. Folder.UserViewManager = Resolve<IUserViewManager>();
  632. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  633. UserView.CollectionManager = Resolve<ICollectionManager>();
  634. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  635. CollectionFolder.XmlSerializer = _xmlSerializer;
  636. CollectionFolder.ApplicationHost = this;
  637. }
  638. /// <summary>
  639. /// Finds plugin components and register them with the appropriate services.
  640. /// </summary>
  641. private void FindParts()
  642. {
  643. if (!ConfigurationManager.Configuration.IsPortAuthorized)
  644. {
  645. ConfigurationManager.Configuration.IsPortAuthorized = true;
  646. ConfigurationManager.SaveConfiguration();
  647. }
  648. _pluginManager.CreatePlugins();
  649. _urlPrefixes = GetUrlPrefixes().ToArray();
  650. Resolve<ILibraryManager>().AddParts(
  651. GetExports<IResolverIgnoreRule>(),
  652. GetExports<IItemResolver>(),
  653. GetExports<IIntroProvider>(),
  654. GetExports<IBaseItemComparer>(),
  655. GetExports<ILibraryPostScanTask>());
  656. Resolve<IProviderManager>().AddParts(
  657. GetExports<IImageProvider>(),
  658. GetExports<IMetadataService>(),
  659. GetExports<IMetadataProvider>(),
  660. GetExports<IMetadataSaver>(),
  661. GetExports<IExternalId>());
  662. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  663. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  664. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  665. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  666. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  667. }
  668. /// <summary>
  669. /// Discovers the types.
  670. /// </summary>
  671. protected void DiscoverTypes()
  672. {
  673. Logger.LogInformation("Loading assemblies");
  674. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  675. }
  676. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  677. {
  678. foreach (var ass in assemblies)
  679. {
  680. Type[] exportedTypes;
  681. try
  682. {
  683. exportedTypes = ass.GetExportedTypes();
  684. }
  685. catch (FileNotFoundException ex)
  686. {
  687. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  688. _pluginManager.FailPlugin(ass);
  689. continue;
  690. }
  691. catch (TypeLoadException ex)
  692. {
  693. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  694. _pluginManager.FailPlugin(ass);
  695. continue;
  696. }
  697. foreach (Type type in exportedTypes)
  698. {
  699. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  700. {
  701. yield return type;
  702. }
  703. }
  704. }
  705. }
  706. private CertificateInfo CertificateInfo { get; set; }
  707. public X509Certificate2 Certificate { get; private set; }
  708. private IEnumerable<string> GetUrlPrefixes()
  709. {
  710. var hosts = new[] { "+" };
  711. return hosts.SelectMany(i =>
  712. {
  713. var prefixes = new List<string>
  714. {
  715. "http://" + i + ":" + HttpPort + "/"
  716. };
  717. if (CertificateInfo != null)
  718. {
  719. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  720. }
  721. return prefixes;
  722. });
  723. }
  724. /// <summary>
  725. /// Called when [configuration updated].
  726. /// </summary>
  727. /// <param name="sender">The sender.</param>
  728. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  729. protected void OnConfigurationUpdated(object sender, EventArgs e)
  730. {
  731. var requiresRestart = false;
  732. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  733. // Don't do anything if these haven't been set yet
  734. if (HttpPort != 0 && HttpsPort != 0)
  735. {
  736. // Need to restart if ports have changed
  737. if (networkConfiguration.HttpServerPortNumber != HttpPort ||
  738. networkConfiguration.HttpsPortNumber != HttpsPort)
  739. {
  740. if (ConfigurationManager.Configuration.IsPortAuthorized)
  741. {
  742. ConfigurationManager.Configuration.IsPortAuthorized = false;
  743. ConfigurationManager.SaveConfiguration();
  744. requiresRestart = true;
  745. }
  746. }
  747. }
  748. if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  749. {
  750. requiresRestart = true;
  751. }
  752. if (ValidateSslCertificate(networkConfiguration))
  753. {
  754. requiresRestart = true;
  755. }
  756. if (requiresRestart)
  757. {
  758. Logger.LogInformation("App needs to be restarted due to configuration change.");
  759. NotifyPendingRestart();
  760. }
  761. }
  762. /// <summary>
  763. /// Validates the SSL certificate.
  764. /// </summary>
  765. /// <param name="networkConfig">The new configuration.</param>
  766. /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
  767. private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
  768. {
  769. var newPath = networkConfig.CertificatePath;
  770. if (!string.IsNullOrWhiteSpace(newPath)
  771. && !string.Equals(CertificateInfo?.Path, newPath, StringComparison.Ordinal))
  772. {
  773. if (File.Exists(newPath))
  774. {
  775. return true;
  776. }
  777. throw new FileNotFoundException(
  778. string.Format(
  779. CultureInfo.InvariantCulture,
  780. "Certificate file '{0}' does not exist.",
  781. newPath));
  782. }
  783. return false;
  784. }
  785. /// <summary>
  786. /// Notifies that the kernel that a change has been made that requires a restart.
  787. /// </summary>
  788. public void NotifyPendingRestart()
  789. {
  790. Logger.LogInformation("App needs to be restarted.");
  791. var changed = !HasPendingRestart;
  792. HasPendingRestart = true;
  793. if (changed)
  794. {
  795. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  796. }
  797. }
  798. /// <summary>
  799. /// Restarts this instance.
  800. /// </summary>
  801. public void Restart()
  802. {
  803. if (!CanSelfRestart)
  804. {
  805. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  806. }
  807. if (IsShuttingDown)
  808. {
  809. return;
  810. }
  811. IsShuttingDown = true;
  812. Task.Run(async () =>
  813. {
  814. try
  815. {
  816. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  817. }
  818. catch (Exception ex)
  819. {
  820. Logger.LogError(ex, "Error sending server restart notification");
  821. }
  822. Logger.LogInformation("Calling RestartInternal");
  823. RestartInternal();
  824. });
  825. }
  826. protected abstract void RestartInternal();
  827. /// <summary>
  828. /// Gets the composable part assemblies.
  829. /// </summary>
  830. /// <returns>IEnumerable{Assembly}.</returns>
  831. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  832. {
  833. foreach (var p in _pluginManager.LoadAssemblies())
  834. {
  835. yield return p;
  836. }
  837. // Include composable parts in the Model assembly
  838. yield return typeof(SystemInfo).Assembly;
  839. // Include composable parts in the Common assembly
  840. yield return typeof(IApplicationHost).Assembly;
  841. // Include composable parts in the Controller assembly
  842. yield return typeof(IServerApplicationHost).Assembly;
  843. // Include composable parts in the Providers assembly
  844. yield return typeof(ProviderUtils).Assembly;
  845. // Include composable parts in the Photos assembly
  846. yield return typeof(PhotoProvider).Assembly;
  847. // Emby.Server implementations
  848. yield return typeof(InstallationManager).Assembly;
  849. // MediaEncoding
  850. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  851. // Dlna
  852. yield return typeof(DlnaEntryPoint).Assembly;
  853. // Local metadata
  854. yield return typeof(BoxSetXmlSaver).Assembly;
  855. // Notifications
  856. yield return typeof(NotificationManager).Assembly;
  857. // Xbmc
  858. yield return typeof(ArtistNfoProvider).Assembly;
  859. // Network
  860. yield return typeof(NetworkManager).Assembly;
  861. foreach (var i in GetAssembliesWithPartsInternal())
  862. {
  863. yield return i;
  864. }
  865. }
  866. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  867. /// <summary>
  868. /// Gets the system status.
  869. /// </summary>
  870. /// <param name="source">Where this request originated.</param>
  871. /// <returns>SystemInfo.</returns>
  872. public SystemInfo GetSystemInfo(IPAddress source)
  873. {
  874. return new SystemInfo
  875. {
  876. HasPendingRestart = HasPendingRestart,
  877. IsShuttingDown = IsShuttingDown,
  878. Version = ApplicationVersionString,
  879. WebSocketPortNumber = HttpPort,
  880. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  881. Id = SystemId,
  882. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  883. WebPath = ApplicationPaths.WebPath,
  884. LogPath = ApplicationPaths.LogDirectoryPath,
  885. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  886. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  887. CachePath = ApplicationPaths.CachePath,
  888. OperatingSystem = MediaBrowser.Common.System.OperatingSystem.Id.ToString(),
  889. OperatingSystemDisplayName = MediaBrowser.Common.System.OperatingSystem.Name,
  890. CanSelfRestart = CanSelfRestart,
  891. CanLaunchWebBrowser = CanLaunchWebBrowser,
  892. TranscodingTempPath = ConfigurationManager.GetTranscodePath(),
  893. ServerName = FriendlyName,
  894. LocalAddress = GetSmartApiUrl(source),
  895. SupportsLibraryMonitor = true,
  896. EncoderLocation = _mediaEncoder.EncoderLocation,
  897. SystemArchitecture = RuntimeInformation.OSArchitecture,
  898. PackageName = _startupOptions.PackageName
  899. };
  900. }
  901. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  902. => NetManager.GetMacAddresses()
  903. .Select(i => new WakeOnLanInfo(i))
  904. .ToList();
  905. public PublicSystemInfo GetPublicSystemInfo(IPAddress address)
  906. {
  907. return new PublicSystemInfo
  908. {
  909. Version = ApplicationVersionString,
  910. ProductName = ApplicationProductName,
  911. Id = SystemId,
  912. OperatingSystem = MediaBrowser.Common.System.OperatingSystem.Id.ToString(),
  913. ServerName = FriendlyName,
  914. LocalAddress = GetSmartApiUrl(address),
  915. StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
  916. };
  917. }
  918. /// <inheritdoc/>
  919. public bool ListenWithHttps => Certificate != null && ConfigurationManager.GetNetworkConfiguration().EnableHttps;
  920. /// <inheritdoc/>
  921. public string GetSmartApiUrl(IPAddress remoteAddr, int? port = null)
  922. {
  923. // Published server ends with a /
  924. if (!string.IsNullOrEmpty(PublishedServerUrl))
  925. {
  926. // Published server ends with a '/', so we need to remove it.
  927. return PublishedServerUrl.Trim('/');
  928. }
  929. string smart = NetManager.GetBindInterface(remoteAddr, out port);
  930. // If the smartAPI doesn't start with http then treat it as a host or ip.
  931. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  932. {
  933. return smart.Trim('/');
  934. }
  935. return GetLocalApiUrl(smart.Trim('/'), null, port);
  936. }
  937. /// <inheritdoc/>
  938. public string GetSmartApiUrl(HttpRequest request, int? port = null)
  939. {
  940. // Published server ends with a /
  941. if (!string.IsNullOrEmpty(PublishedServerUrl))
  942. {
  943. // Published server ends with a '/', so we need to remove it.
  944. return PublishedServerUrl.Trim('/');
  945. }
  946. string smart = NetManager.GetBindInterface(request, out port);
  947. // If the smartAPI doesn't start with http then treat it as a host or ip.
  948. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  949. {
  950. return smart.Trim('/');
  951. }
  952. return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port);
  953. }
  954. /// <inheritdoc/>
  955. public string GetSmartApiUrl(string hostname, int? port = null)
  956. {
  957. // Published server ends with a /
  958. if (!string.IsNullOrEmpty(PublishedServerUrl))
  959. {
  960. // Published server ends with a '/', so we need to remove it.
  961. return PublishedServerUrl.Trim('/');
  962. }
  963. string smart = NetManager.GetBindInterface(hostname, out port);
  964. // If the smartAPI doesn't start with http then treat it as a host or ip.
  965. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  966. {
  967. return smart.Trim('/');
  968. }
  969. return GetLocalApiUrl(smart.Trim('/'), null, port);
  970. }
  971. /// <inheritdoc/>
  972. public string GetLoopbackHttpApiUrl()
  973. {
  974. if (NetManager.IsIP6Enabled)
  975. {
  976. return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort);
  977. }
  978. return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
  979. }
  980. /// <inheritdoc/>
  981. public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
  982. {
  983. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  984. // not. For consistency, always trim the trailing slash.
  985. return new UriBuilder
  986. {
  987. Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
  988. Host = hostname,
  989. Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
  990. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  991. }.ToString().TrimEnd('/');
  992. }
  993. public string FriendlyName =>
  994. string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName)
  995. ? Environment.MachineName
  996. : ConfigurationManager.Configuration.ServerName;
  997. /// <summary>
  998. /// Shuts down.
  999. /// </summary>
  1000. public async Task Shutdown()
  1001. {
  1002. if (IsShuttingDown)
  1003. {
  1004. return;
  1005. }
  1006. IsShuttingDown = true;
  1007. try
  1008. {
  1009. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1010. }
  1011. catch (Exception ex)
  1012. {
  1013. Logger.LogError(ex, "Error sending server shutdown notification");
  1014. }
  1015. ShutdownInternal();
  1016. }
  1017. protected abstract void ShutdownInternal();
  1018. public IEnumerable<Assembly> GetApiPluginAssemblies()
  1019. {
  1020. var assemblies = _allConcreteTypes
  1021. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  1022. .Select(i => i.Assembly)
  1023. .Distinct();
  1024. foreach (var assembly in assemblies)
  1025. {
  1026. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  1027. yield return assembly;
  1028. }
  1029. }
  1030. public virtual void LaunchUrl(string url)
  1031. {
  1032. if (!CanLaunchWebBrowser)
  1033. {
  1034. throw new NotSupportedException();
  1035. }
  1036. var process = new Process
  1037. {
  1038. StartInfo = new ProcessStartInfo
  1039. {
  1040. FileName = url,
  1041. UseShellExecute = true,
  1042. ErrorDialog = false
  1043. },
  1044. EnableRaisingEvents = true
  1045. };
  1046. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1047. try
  1048. {
  1049. process.Start();
  1050. }
  1051. catch (Exception ex)
  1052. {
  1053. Logger.LogError(ex, "Error launching url: {url}", url);
  1054. throw;
  1055. }
  1056. }
  1057. private bool _disposed = false;
  1058. /// <summary>
  1059. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1060. /// </summary>
  1061. public void Dispose()
  1062. {
  1063. Dispose(true);
  1064. GC.SuppressFinalize(this);
  1065. }
  1066. /// <summary>
  1067. /// Releases unmanaged and - optionally - managed resources.
  1068. /// </summary>
  1069. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1070. protected virtual void Dispose(bool dispose)
  1071. {
  1072. if (_disposed)
  1073. {
  1074. return;
  1075. }
  1076. if (dispose)
  1077. {
  1078. var type = GetType();
  1079. Logger.LogInformation("Disposing {Type}", type.Name);
  1080. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1081. _disposableParts.Clear();
  1082. foreach (var part in parts)
  1083. {
  1084. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1085. try
  1086. {
  1087. part.Dispose();
  1088. }
  1089. catch (Exception ex)
  1090. {
  1091. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1092. }
  1093. }
  1094. }
  1095. _disposed = true;
  1096. }
  1097. }
  1098. internal class CertificateInfo
  1099. {
  1100. public string Path { get; set; }
  1101. public string Password { get; set; }
  1102. }
  1103. }