ApplicationHost.cs 55 KB

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