ApplicationHost.cs 56 KB

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