ApplicationHost.cs 51 KB

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