ApplicationHost.cs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  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<IResourceFileManager, ResourceFileManager>();
  515. ServiceCollection.AddSingleton<EncodingHelper>();
  516. ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  517. ServiceCollection.AddSingleton<TranscodingJobHelper>();
  518. ServiceCollection.AddScoped<MediaInfoHelper>();
  519. ServiceCollection.AddScoped<AudioHelper>();
  520. ServiceCollection.AddScoped<DynamicHlsHelper>();
  521. }
  522. /// <summary>
  523. /// Create services registered with the service container that need to be initialized at application startup.
  524. /// </summary>
  525. /// <returns>A task representing the service initialization operation.</returns>
  526. public async Task InitializeServices()
  527. {
  528. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  529. await localizationManager.LoadAll().ConfigureAwait(false);
  530. _mediaEncoder = Resolve<IMediaEncoder>();
  531. _sessionManager = Resolve<ISessionManager>();
  532. _httpClientFactory = Resolve<IHttpClientFactory>();
  533. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  534. SetStaticProperties();
  535. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  536. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  537. FindParts();
  538. }
  539. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  540. {
  541. // Distinct these to prevent users from reporting problems that aren't actually problems
  542. var commandLineArgs = Environment
  543. .GetCommandLineArgs()
  544. .Distinct();
  545. // Get all relevant environment variables
  546. var allEnvVars = Environment.GetEnvironmentVariables();
  547. var relevantEnvVars = new Dictionary<object, object>();
  548. foreach (var key in allEnvVars.Keys)
  549. {
  550. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  551. {
  552. relevantEnvVars.Add(key, allEnvVars[key]);
  553. }
  554. }
  555. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  556. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  557. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  558. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  559. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  560. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  561. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  562. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  563. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  564. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  565. }
  566. private X509Certificate2 GetCertificate(CertificateInfo info)
  567. {
  568. var certificateLocation = info?.Path;
  569. if (string.IsNullOrWhiteSpace(certificateLocation))
  570. {
  571. return null;
  572. }
  573. try
  574. {
  575. if (!File.Exists(certificateLocation))
  576. {
  577. return null;
  578. }
  579. // Don't use an empty string password
  580. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  581. var localCert = new X509Certificate2(certificateLocation, password);
  582. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  583. if (!localCert.HasPrivateKey)
  584. {
  585. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  586. return null;
  587. }
  588. return localCert;
  589. }
  590. catch (Exception ex)
  591. {
  592. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  593. return null;
  594. }
  595. }
  596. /// <summary>
  597. /// Dirty hacks.
  598. /// </summary>
  599. private void SetStaticProperties()
  600. {
  601. // For now there's no real way to inject these properly
  602. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  603. BaseItem.ConfigurationManager = ServerConfigurationManager;
  604. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  605. BaseItem.ProviderManager = Resolve<IProviderManager>();
  606. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  607. BaseItem.ItemRepository = Resolve<IItemRepository>();
  608. BaseItem.FileSystem = _fileSystemManager;
  609. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  610. BaseItem.ChannelManager = Resolve<IChannelManager>();
  611. Video.LiveTvManager = Resolve<ILiveTvManager>();
  612. Folder.UserViewManager = Resolve<IUserViewManager>();
  613. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  614. UserView.CollectionManager = Resolve<ICollectionManager>();
  615. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  616. CollectionFolder.XmlSerializer = _xmlSerializer;
  617. CollectionFolder.JsonSerializer = Resolve<IJsonSerializer>();
  618. CollectionFolder.ApplicationHost = this;
  619. }
  620. /// <summary>
  621. /// Finds plugin components and register them with the appropriate services.
  622. /// </summary>
  623. private void FindParts()
  624. {
  625. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  626. {
  627. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  628. ConfigurationManager.SaveConfiguration();
  629. }
  630. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  631. _plugins = GetExports<IPlugin>()
  632. .Where(i => i != null)
  633. .ToArray();
  634. if (Plugins != null)
  635. {
  636. var pluginBuilder = new StringBuilder();
  637. foreach (var plugin in Plugins)
  638. {
  639. pluginBuilder.Append(plugin.Name)
  640. .Append(' ')
  641. .Append(plugin.Version)
  642. .AppendLine();
  643. }
  644. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  645. }
  646. _urlPrefixes = GetUrlPrefixes().ToArray();
  647. Resolve<ILibraryManager>().AddParts(
  648. GetExports<IResolverIgnoreRule>(),
  649. GetExports<IItemResolver>(),
  650. GetExports<IIntroProvider>(),
  651. GetExports<IBaseItemComparer>(),
  652. GetExports<ILibraryPostScanTask>());
  653. Resolve<IProviderManager>().AddParts(
  654. GetExports<IImageProvider>(),
  655. GetExports<IMetadataService>(),
  656. GetExports<IMetadataProvider>(),
  657. GetExports<IMetadataSaver>(),
  658. GetExports<IExternalId>());
  659. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  660. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  661. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  662. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  663. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  664. Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>());
  665. }
  666. /// <summary>
  667. /// Discovers the types.
  668. /// </summary>
  669. protected void DiscoverTypes()
  670. {
  671. Logger.LogInformation("Loading assemblies");
  672. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  673. }
  674. private void RegisterPluginServices()
  675. {
  676. foreach (var pluginServiceRegistrator in GetExportTypes<IPluginServiceRegistrator>())
  677. {
  678. try
  679. {
  680. var instance = (IPluginServiceRegistrator)Activator.CreateInstance(pluginServiceRegistrator);
  681. instance.RegisterServices(ServiceCollection);
  682. }
  683. catch (Exception ex)
  684. {
  685. Logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly);
  686. }
  687. }
  688. }
  689. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  690. {
  691. foreach (var ass in assemblies)
  692. {
  693. Type[] exportedTypes;
  694. try
  695. {
  696. exportedTypes = ass.GetExportedTypes();
  697. }
  698. catch (FileNotFoundException ex)
  699. {
  700. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  701. continue;
  702. }
  703. catch (TypeLoadException ex)
  704. {
  705. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  706. continue;
  707. }
  708. foreach (Type type in exportedTypes)
  709. {
  710. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  711. {
  712. yield return type;
  713. }
  714. }
  715. }
  716. }
  717. private CertificateInfo CertificateInfo { get; set; }
  718. public X509Certificate2 Certificate { get; private set; }
  719. private IEnumerable<string> GetUrlPrefixes()
  720. {
  721. var hosts = new[] { "+" };
  722. return hosts.SelectMany(i =>
  723. {
  724. var prefixes = new List<string>
  725. {
  726. "http://" + i + ":" + HttpPort + "/"
  727. };
  728. if (CertificateInfo != null)
  729. {
  730. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  731. }
  732. return prefixes;
  733. });
  734. }
  735. /// <summary>
  736. /// Called when [configuration updated].
  737. /// </summary>
  738. /// <param name="sender">The sender.</param>
  739. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  740. protected void OnConfigurationUpdated(object sender, EventArgs e)
  741. {
  742. var requiresRestart = false;
  743. // Don't do anything if these haven't been set yet
  744. if (HttpPort != 0 && HttpsPort != 0)
  745. {
  746. var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration();
  747. // Need to restart if ports have changed
  748. if (networkConfiguration.HttpServerPortNumber != HttpPort ||
  749. networkConfiguration.HttpsPortNumber != HttpsPort)
  750. {
  751. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  752. {
  753. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  754. ServerConfigurationManager.SaveConfiguration();
  755. requiresRestart = true;
  756. }
  757. }
  758. }
  759. if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  760. {
  761. requiresRestart = true;
  762. }
  763. var currentCertPath = CertificateInfo?.Path;
  764. var newCertPath = ServerConfigurationManager.Configuration.CertificatePath;
  765. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  766. {
  767. requiresRestart = true;
  768. }
  769. if (requiresRestart)
  770. {
  771. Logger.LogInformation("App needs to be restarted due to configuration change.");
  772. NotifyPendingRestart();
  773. }
  774. }
  775. /// <summary>
  776. /// Notifies that the kernel that a change has been made that requires a restart.
  777. /// </summary>
  778. public void NotifyPendingRestart()
  779. {
  780. Logger.LogInformation("App needs to be restarted.");
  781. var changed = !HasPendingRestart;
  782. HasPendingRestart = true;
  783. if (changed)
  784. {
  785. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  786. }
  787. }
  788. /// <summary>
  789. /// Restarts this instance.
  790. /// </summary>
  791. public void Restart()
  792. {
  793. if (!CanSelfRestart)
  794. {
  795. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  796. }
  797. if (IsShuttingDown)
  798. {
  799. return;
  800. }
  801. IsShuttingDown = true;
  802. Task.Run(async () =>
  803. {
  804. try
  805. {
  806. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  807. }
  808. catch (Exception ex)
  809. {
  810. Logger.LogError(ex, "Error sending server restart notification");
  811. }
  812. Logger.LogInformation("Calling RestartInternal");
  813. RestartInternal();
  814. });
  815. }
  816. protected abstract void RestartInternal();
  817. /// <inheritdoc/>
  818. public IEnumerable<LocalPlugin> GetLocalPlugins(string path, bool cleanup = true)
  819. {
  820. var minimumVersion = new Version(0, 0, 0, 1);
  821. var versions = new List<LocalPlugin>();
  822. if (!Directory.Exists(path))
  823. {
  824. // Plugin path doesn't exist, don't try to enumerate subfolders.
  825. return Enumerable.Empty<LocalPlugin>();
  826. }
  827. var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly);
  828. foreach (var dir in directories)
  829. {
  830. try
  831. {
  832. var metafile = Path.Combine(dir, "meta.json");
  833. if (File.Exists(metafile))
  834. {
  835. var manifest = _jsonSerializer.DeserializeFromFile<PluginManifest>(metafile);
  836. if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
  837. {
  838. targetAbi = minimumVersion;
  839. }
  840. if (!Version.TryParse(manifest.Version, out var version))
  841. {
  842. version = minimumVersion;
  843. }
  844. if (ApplicationVersion >= targetAbi)
  845. {
  846. // Only load Plugins if the plugin is built for this version or below.
  847. versions.Add(new LocalPlugin(manifest.Guid, manifest.Name, version, dir));
  848. }
  849. }
  850. else
  851. {
  852. // No metafile, so lets see if the folder is versioned.
  853. metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
  854. int versionIndex = dir.LastIndexOf('_');
  855. if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version parsedVersion))
  856. {
  857. // Versioned folder.
  858. versions.Add(new LocalPlugin(Guid.Empty, metafile, parsedVersion, dir));
  859. }
  860. else
  861. {
  862. // Un-versioned folder - Add it under the path name and version 0.0.0.1.
  863. versions.Add(new LocalPlugin(Guid.Empty, metafile, minimumVersion, dir));
  864. }
  865. }
  866. }
  867. catch
  868. {
  869. continue;
  870. }
  871. }
  872. string lastName = string.Empty;
  873. versions.Sort(LocalPlugin.Compare);
  874. // Traverse backwards through the list.
  875. // The first item will be the latest version.
  876. for (int x = versions.Count - 1; x >= 0; x--)
  877. {
  878. if (!string.Equals(lastName, versions[x].Name, StringComparison.OrdinalIgnoreCase))
  879. {
  880. versions[x].DllFiles.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories));
  881. lastName = versions[x].Name;
  882. continue;
  883. }
  884. if (!string.IsNullOrEmpty(lastName) && cleanup)
  885. {
  886. // Attempt a cleanup of old folders.
  887. try
  888. {
  889. Logger.LogDebug("Deleting {Path}", versions[x].Path);
  890. Directory.Delete(versions[x].Path, true);
  891. }
  892. catch (Exception e)
  893. {
  894. Logger.LogWarning(e, "Unable to delete {Path}", versions[x].Path);
  895. }
  896. versions.RemoveAt(x);
  897. }
  898. }
  899. return versions;
  900. }
  901. /// <summary>
  902. /// Gets the composable part assemblies.
  903. /// </summary>
  904. /// <returns>IEnumerable{Assembly}.</returns>
  905. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  906. {
  907. if (Directory.Exists(ApplicationPaths.PluginsPath))
  908. {
  909. foreach (var plugin in GetLocalPlugins(ApplicationPaths.PluginsPath))
  910. {
  911. foreach (var file in plugin.DllFiles)
  912. {
  913. Assembly plugAss;
  914. try
  915. {
  916. plugAss = Assembly.LoadFrom(file);
  917. }
  918. catch (FileLoadException ex)
  919. {
  920. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  921. continue;
  922. }
  923. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  924. yield return plugAss;
  925. }
  926. }
  927. }
  928. // Include composable parts in the Model assembly
  929. yield return typeof(SystemInfo).Assembly;
  930. // Include composable parts in the Common assembly
  931. yield return typeof(IApplicationHost).Assembly;
  932. // Include composable parts in the Controller assembly
  933. yield return typeof(IServerApplicationHost).Assembly;
  934. // Include composable parts in the Providers assembly
  935. yield return typeof(ProviderUtils).Assembly;
  936. // Include composable parts in the Photos assembly
  937. yield return typeof(PhotoProvider).Assembly;
  938. // Emby.Server implementations
  939. yield return typeof(InstallationManager).Assembly;
  940. // MediaEncoding
  941. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  942. // Dlna
  943. yield return typeof(DlnaEntryPoint).Assembly;
  944. // Local metadata
  945. yield return typeof(BoxSetXmlSaver).Assembly;
  946. // Notifications
  947. yield return typeof(NotificationManager).Assembly;
  948. // Xbmc
  949. yield return typeof(ArtistNfoProvider).Assembly;
  950. // Network
  951. yield return typeof(NetworkManager).Assembly;
  952. foreach (var i in GetAssembliesWithPartsInternal())
  953. {
  954. yield return i;
  955. }
  956. }
  957. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  958. /// <summary>
  959. /// Gets the system status.
  960. /// </summary>
  961. /// <param name="source">Where this request originated.</param>
  962. /// <returns>SystemInfo.</returns>
  963. public SystemInfo GetSystemInfo(IPAddress source)
  964. {
  965. return new SystemInfo
  966. {
  967. HasPendingRestart = HasPendingRestart,
  968. IsShuttingDown = IsShuttingDown,
  969. Version = ApplicationVersionString,
  970. WebSocketPortNumber = HttpPort,
  971. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  972. Id = SystemId,
  973. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  974. WebPath = ApplicationPaths.WebPath,
  975. LogPath = ApplicationPaths.LogDirectoryPath,
  976. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  977. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  978. CachePath = ApplicationPaths.CachePath,
  979. OperatingSystem = OperatingSystem.Id.ToString(),
  980. OperatingSystemDisplayName = OperatingSystem.Name,
  981. CanSelfRestart = CanSelfRestart,
  982. CanLaunchWebBrowser = CanLaunchWebBrowser,
  983. HasUpdateAvailable = HasUpdateAvailable,
  984. TranscodingTempPath = ConfigurationManager.GetTranscodePath(),
  985. ServerName = FriendlyName,
  986. LocalAddress = GetSmartApiUrl(source),
  987. SupportsLibraryMonitor = true,
  988. EncoderLocation = _mediaEncoder.EncoderLocation,
  989. SystemArchitecture = RuntimeInformation.OSArchitecture,
  990. PackageName = _startupOptions.PackageName
  991. };
  992. }
  993. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  994. => NetManager.GetMacAddresses()
  995. .Select(i => new WakeOnLanInfo(i))
  996. .ToList();
  997. public PublicSystemInfo GetPublicSystemInfo(IPAddress source)
  998. {
  999. return new PublicSystemInfo
  1000. {
  1001. Version = ApplicationVersionString,
  1002. ProductName = ApplicationProductName,
  1003. Id = SystemId,
  1004. OperatingSystem = OperatingSystem.Id.ToString(),
  1005. ServerName = FriendlyName,
  1006. LocalAddress = GetSmartApiUrl(source),
  1007. StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
  1008. };
  1009. }
  1010. /// <inheritdoc/>
  1011. public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.GetNetworkConfiguration().EnableHttps;
  1012. /// <inheritdoc/>
  1013. public string GetSmartApiUrl(IPAddress ipAddress, int? port = null)
  1014. {
  1015. // Published server ends with a /
  1016. if (_startupOptions.PublishedServerUrl != null)
  1017. {
  1018. // Published server ends with a '/', so we need to remove it.
  1019. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1020. }
  1021. string smart = NetManager.GetBindInterface(ipAddress, out port);
  1022. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1023. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1024. {
  1025. return smart.Trim('/');
  1026. }
  1027. return GetLocalApiUrl(smart.Trim('/'), null, port);
  1028. }
  1029. /// <inheritdoc/>
  1030. public string GetSmartApiUrl(HttpRequest request, int? port = null)
  1031. {
  1032. // Published server ends with a /
  1033. if (_startupOptions.PublishedServerUrl != null)
  1034. {
  1035. // Published server ends with a '/', so we need to remove it.
  1036. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1037. }
  1038. string smart = NetManager.GetBindInterface(request, out port);
  1039. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1040. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1041. {
  1042. return smart.Trim('/');
  1043. }
  1044. return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port);
  1045. }
  1046. /// <inheritdoc/>
  1047. public string GetSmartApiUrl(string hostname, int? port = null)
  1048. {
  1049. // Published server ends with a /
  1050. if (_startupOptions.PublishedServerUrl != null)
  1051. {
  1052. // Published server ends with a '/', so we need to remove it.
  1053. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1054. }
  1055. string smart = NetManager.GetBindInterface(hostname, out port);
  1056. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1057. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1058. {
  1059. return smart.Trim('/');
  1060. }
  1061. return GetLocalApiUrl(smart.Trim('/'), null, port);
  1062. }
  1063. /// <inheritdoc/>
  1064. public string GetLoopbackHttpApiUrl()
  1065. {
  1066. if (NetManager.IsIP6Enabled)
  1067. {
  1068. return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort);
  1069. }
  1070. return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
  1071. }
  1072. /// <inheritdoc/>
  1073. public string GetLocalApiUrl(string host, string scheme = null, int? port = null)
  1074. {
  1075. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  1076. // not. For consistency, always trim the trailing slash.
  1077. return new UriBuilder
  1078. {
  1079. Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
  1080. Host = host,
  1081. Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
  1082. Path = ServerConfigurationManager.GetNetworkConfiguration().BaseUrl
  1083. }.ToString().TrimEnd('/');
  1084. }
  1085. public string FriendlyName =>
  1086. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1087. ? Environment.MachineName
  1088. : ServerConfigurationManager.Configuration.ServerName;
  1089. /// <summary>
  1090. /// Shuts down.
  1091. /// </summary>
  1092. public async Task Shutdown()
  1093. {
  1094. if (IsShuttingDown)
  1095. {
  1096. return;
  1097. }
  1098. IsShuttingDown = true;
  1099. try
  1100. {
  1101. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1102. }
  1103. catch (Exception ex)
  1104. {
  1105. Logger.LogError(ex, "Error sending server shutdown notification");
  1106. }
  1107. ShutdownInternal();
  1108. }
  1109. protected abstract void ShutdownInternal();
  1110. public event EventHandler HasUpdateAvailableChanged;
  1111. private bool _hasUpdateAvailable;
  1112. public bool HasUpdateAvailable
  1113. {
  1114. get => _hasUpdateAvailable;
  1115. set
  1116. {
  1117. var fireEvent = value && !_hasUpdateAvailable;
  1118. _hasUpdateAvailable = value;
  1119. if (fireEvent)
  1120. {
  1121. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1122. }
  1123. }
  1124. }
  1125. /// <summary>
  1126. /// Removes the plugin.
  1127. /// </summary>
  1128. /// <param name="plugin">The plugin.</param>
  1129. public void RemovePlugin(IPlugin plugin)
  1130. {
  1131. var list = _plugins.ToList();
  1132. list.Remove(plugin);
  1133. _plugins = list.ToArray();
  1134. }
  1135. public IEnumerable<Assembly> GetApiPluginAssemblies()
  1136. {
  1137. var assemblies = _allConcreteTypes
  1138. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  1139. .Select(i => i.Assembly)
  1140. .Distinct();
  1141. foreach (var assembly in assemblies)
  1142. {
  1143. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  1144. yield return assembly;
  1145. }
  1146. }
  1147. public virtual void LaunchUrl(string url)
  1148. {
  1149. if (!CanLaunchWebBrowser)
  1150. {
  1151. throw new NotSupportedException();
  1152. }
  1153. var process = new Process
  1154. {
  1155. StartInfo = new ProcessStartInfo
  1156. {
  1157. FileName = url,
  1158. UseShellExecute = true,
  1159. ErrorDialog = false
  1160. },
  1161. EnableRaisingEvents = true
  1162. };
  1163. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1164. try
  1165. {
  1166. process.Start();
  1167. }
  1168. catch (Exception ex)
  1169. {
  1170. Logger.LogError(ex, "Error launching url: {url}", url);
  1171. throw;
  1172. }
  1173. }
  1174. private bool _disposed = false;
  1175. /// <summary>
  1176. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1177. /// </summary>
  1178. public void Dispose()
  1179. {
  1180. Dispose(true);
  1181. GC.SuppressFinalize(this);
  1182. }
  1183. /// <summary>
  1184. /// Releases unmanaged and - optionally - managed resources.
  1185. /// </summary>
  1186. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1187. protected virtual void Dispose(bool dispose)
  1188. {
  1189. if (_disposed)
  1190. {
  1191. return;
  1192. }
  1193. if (dispose)
  1194. {
  1195. var type = GetType();
  1196. Logger.LogInformation("Disposing {Type}", type.Name);
  1197. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1198. _disposableParts.Clear();
  1199. foreach (var part in parts)
  1200. {
  1201. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1202. try
  1203. {
  1204. part.Dispose();
  1205. }
  1206. catch (Exception ex)
  1207. {
  1208. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1209. }
  1210. }
  1211. }
  1212. _disposed = true;
  1213. }
  1214. }
  1215. internal class CertificateInfo
  1216. {
  1217. public string Path { get; set; }
  1218. public string Password { get; set; }
  1219. }
  1220. }