ApplicationHost.cs 51 KB

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