ApplicationHost.cs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Net.Sockets;
  12. using System.Reflection;
  13. using System.Runtime.InteropServices;
  14. using System.Security.Cryptography.X509Certificates;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  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;
  33. using Emby.Server.Implementations.HttpServer.Security;
  34. using Emby.Server.Implementations.IO;
  35. using Emby.Server.Implementations.Library;
  36. using Emby.Server.Implementations.LiveTv;
  37. using Emby.Server.Implementations.Localization;
  38. using Emby.Server.Implementations.Net;
  39. using Emby.Server.Implementations.Playlists;
  40. using Emby.Server.Implementations.Plugins;
  41. using Emby.Server.Implementations.QuickConnect;
  42. using Emby.Server.Implementations.ScheduledTasks;
  43. using Emby.Server.Implementations.Security;
  44. using Emby.Server.Implementations.Serialization;
  45. using Emby.Server.Implementations.Session;
  46. using Emby.Server.Implementations.SyncPlay;
  47. using Emby.Server.Implementations.TV;
  48. using Emby.Server.Implementations.Updates;
  49. using Jellyfin.Api.Helpers;
  50. using MediaBrowser.Common;
  51. using MediaBrowser.Common.Configuration;
  52. using MediaBrowser.Common.Events;
  53. using MediaBrowser.Common.Json;
  54. using MediaBrowser.Common.Net;
  55. using MediaBrowser.Common.Plugins;
  56. using MediaBrowser.Common.Updates;
  57. using MediaBrowser.Controller;
  58. using MediaBrowser.Controller.Channels;
  59. using MediaBrowser.Controller.Chapters;
  60. using MediaBrowser.Controller.Collections;
  61. using MediaBrowser.Controller.Configuration;
  62. using MediaBrowser.Controller.Devices;
  63. using MediaBrowser.Controller.Dlna;
  64. using MediaBrowser.Controller.Drawing;
  65. using MediaBrowser.Controller.Dto;
  66. using MediaBrowser.Controller.Entities;
  67. using MediaBrowser.Controller.Library;
  68. using MediaBrowser.Controller.LiveTv;
  69. using MediaBrowser.Controller.MediaEncoding;
  70. using MediaBrowser.Controller.Net;
  71. using MediaBrowser.Controller.Notifications;
  72. using MediaBrowser.Controller.Persistence;
  73. using MediaBrowser.Controller.Playlists;
  74. using MediaBrowser.Controller.Plugins;
  75. using MediaBrowser.Controller.Providers;
  76. using MediaBrowser.Controller.QuickConnect;
  77. using MediaBrowser.Controller.Resolvers;
  78. using MediaBrowser.Controller.Security;
  79. using MediaBrowser.Controller.Session;
  80. using MediaBrowser.Controller.Sorting;
  81. using MediaBrowser.Controller.Subtitles;
  82. using MediaBrowser.Controller.SyncPlay;
  83. using MediaBrowser.Controller.TV;
  84. using MediaBrowser.LocalMetadata.Savers;
  85. using MediaBrowser.MediaEncoding.BdInfo;
  86. using MediaBrowser.Model.Configuration;
  87. using MediaBrowser.Model.Cryptography;
  88. using MediaBrowser.Model.Dlna;
  89. using MediaBrowser.Model.Globalization;
  90. using MediaBrowser.Model.IO;
  91. using MediaBrowser.Model.MediaInfo;
  92. using MediaBrowser.Model.Net;
  93. using MediaBrowser.Model.Serialization;
  94. using MediaBrowser.Model.System;
  95. using MediaBrowser.Model.Tasks;
  96. using MediaBrowser.Providers.Chapters;
  97. using MediaBrowser.Providers.Manager;
  98. using MediaBrowser.Providers.Plugins.TheTvdb;
  99. using MediaBrowser.Providers.Plugins.Tmdb;
  100. using MediaBrowser.Providers.Subtitles;
  101. using MediaBrowser.XbmcMetadata.Providers;
  102. using Microsoft.AspNetCore.Mvc;
  103. using Microsoft.Extensions.DependencyInjection;
  104. using Microsoft.Extensions.Logging;
  105. using Prometheus.DotNetRuntime;
  106. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  107. using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
  108. namespace Emby.Server.Implementations
  109. {
  110. /// <summary>
  111. /// Class CompositionRoot.
  112. /// </summary>
  113. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  114. {
  115. /// <summary>
  116. /// The environment variable prefixes to log at server startup.
  117. /// </summary>
  118. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  119. private readonly IFileSystem _fileSystemManager;
  120. private readonly INetworkManager _networkManager;
  121. private readonly IXmlSerializer _xmlSerializer;
  122. private readonly IJsonSerializer _jsonSerializer;
  123. private readonly IStartupOptions _startupOptions;
  124. private IMediaEncoder _mediaEncoder;
  125. private ISessionManager _sessionManager;
  126. private IHttpClientFactory _httpClientFactory;
  127. private IWebSocketManager _webSocketManager;
  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. /// Occurs when [has pending restart changed].
  156. /// </summary>
  157. public event EventHandler HasPendingRestartChanged;
  158. /// <summary>
  159. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  160. /// </summary>
  161. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  162. public bool HasPendingRestart { get; private set; }
  163. /// <inheritdoc />
  164. public bool IsShuttingDown { get; private set; }
  165. /// <summary>
  166. /// Gets the logger.
  167. /// </summary>
  168. protected ILogger<ApplicationHost> Logger { get; }
  169. protected IServiceCollection ServiceCollection { get; }
  170. private IPlugin[] _plugins;
  171. /// <summary>
  172. /// Gets the plugins.
  173. /// </summary>
  174. /// <value>The plugins.</value>
  175. public IReadOnlyList<IPlugin> Plugins => _plugins;
  176. /// <summary>
  177. /// Gets the logger factory.
  178. /// </summary>
  179. protected ILoggerFactory LoggerFactory { get; }
  180. /// <summary>
  181. /// Gets or sets the application paths.
  182. /// </summary>
  183. /// <value>The application paths.</value>
  184. protected IServerApplicationPaths ApplicationPaths { get; set; }
  185. /// <summary>
  186. /// Gets or sets all concrete types.
  187. /// </summary>
  188. /// <value>All concrete types.</value>
  189. private Type[] _allConcreteTypes;
  190. /// <summary>
  191. /// The disposable parts.
  192. /// </summary>
  193. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  194. /// <summary>
  195. /// Gets the configuration manager.
  196. /// </summary>
  197. /// <value>The configuration manager.</value>
  198. protected IConfigurationManager ConfigurationManager { get; set; }
  199. /// <summary>
  200. /// Gets or sets the service provider.
  201. /// </summary>
  202. public IServiceProvider ServiceProvider { get; set; }
  203. /// <summary>
  204. /// Gets the http port for the webhost.
  205. /// </summary>
  206. public int HttpPort { get; private set; }
  207. /// <summary>
  208. /// Gets the https port for the webhost.
  209. /// </summary>
  210. public int HttpsPort { get; private set; }
  211. /// <summary>
  212. /// Gets the server configuration manager.
  213. /// </summary>
  214. /// <value>The server configuration manager.</value>
  215. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  216. /// <summary>
  217. /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
  218. /// </summary>
  219. /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
  220. /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
  221. /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
  222. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  223. /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
  224. /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
  225. public ApplicationHost(
  226. IServerApplicationPaths applicationPaths,
  227. ILoggerFactory loggerFactory,
  228. IStartupOptions options,
  229. IFileSystem fileSystem,
  230. INetworkManager networkManager,
  231. IServiceCollection serviceCollection)
  232. {
  233. _xmlSerializer = new MyXmlSerializer();
  234. _jsonSerializer = new JsonSerializer();
  235. ServiceCollection = serviceCollection;
  236. _networkManager = networkManager;
  237. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  238. ApplicationPaths = applicationPaths;
  239. LoggerFactory = loggerFactory;
  240. _fileSystemManager = fileSystem;
  241. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
  242. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  243. _startupOptions = options;
  244. // Initialize runtime stat collection
  245. if (ServerConfigurationManager.Configuration.EnableMetrics)
  246. {
  247. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  248. }
  249. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  250. _networkManager.NetworkChanged += OnNetworkChanged;
  251. CertificateInfo = new CertificateInfo
  252. {
  253. Path = ServerConfigurationManager.Configuration.CertificatePath,
  254. Password = ServerConfigurationManager.Configuration.CertificatePassword
  255. };
  256. Certificate = GetCertificate(CertificateInfo);
  257. ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
  258. ApplicationVersionString = ApplicationVersion.ToString(3);
  259. ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  260. }
  261. public string ExpandVirtualPath(string path)
  262. {
  263. var appPaths = ApplicationPaths;
  264. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  265. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  266. }
  267. public string ReverseVirtualPath(string path)
  268. {
  269. var appPaths = ApplicationPaths;
  270. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  271. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  272. }
  273. private string[] GetConfiguredLocalSubnets()
  274. {
  275. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  276. }
  277. private void OnNetworkChanged(object sender, EventArgs e)
  278. {
  279. _validAddressResults.Clear();
  280. }
  281. /// <inheritdoc />
  282. public Version ApplicationVersion { get; }
  283. /// <inheritdoc />
  284. public string ApplicationVersionString { get; }
  285. /// <summary>
  286. /// Gets the current application user agent.
  287. /// </summary>
  288. /// <value>The application user agent.</value>
  289. public string ApplicationUserAgent { get; }
  290. /// <summary>
  291. /// Gets the email address for use within a comment section of a user agent field.
  292. /// Presently used to provide contact information to MusicBrainz service.
  293. /// </summary>
  294. public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
  295. /// <summary>
  296. /// Gets the current application name.
  297. /// </summary>
  298. /// <value>The application name.</value>
  299. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  300. private DeviceId _deviceId;
  301. public string SystemId
  302. {
  303. get
  304. {
  305. if (_deviceId == null)
  306. {
  307. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  308. }
  309. return _deviceId.Value;
  310. }
  311. }
  312. /// <inheritdoc/>
  313. public string Name => ApplicationProductName;
  314. /// <summary>
  315. /// Creates an instance of type and resolves all constructor dependencies.
  316. /// </summary>
  317. /// <param name="type">The type.</param>
  318. /// <returns>System.Object.</returns>
  319. public object CreateInstance(Type type)
  320. => ActivatorUtilities.CreateInstance(ServiceProvider, type);
  321. /// <summary>
  322. /// Creates an instance of type and resolves all constructor dependencies.
  323. /// </summary>
  324. /// /// <typeparam name="T">The type.</typeparam>
  325. /// <returns>T.</returns>
  326. public T CreateInstance<T>()
  327. => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
  328. /// <summary>
  329. /// Creates the instance safe.
  330. /// </summary>
  331. /// <param name="type">The type.</param>
  332. /// <returns>System.Object.</returns>
  333. protected object CreateInstanceSafe(Type type)
  334. {
  335. try
  336. {
  337. Logger.LogDebug("Creating instance of {Type}", type);
  338. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  339. }
  340. catch (Exception ex)
  341. {
  342. Logger.LogError(ex, "Error creating {Type}", type);
  343. return null;
  344. }
  345. }
  346. /// <summary>
  347. /// Resolves this instance.
  348. /// </summary>
  349. /// <typeparam name="T">The type</typeparam>
  350. /// <returns>``0.</returns>
  351. public T Resolve<T>() => ServiceProvider.GetService<T>();
  352. /// <summary>
  353. /// Gets the export types.
  354. /// </summary>
  355. /// <typeparam name="T">The type.</typeparam>
  356. /// <returns>IEnumerable{Type}.</returns>
  357. public IEnumerable<Type> GetExportTypes<T>()
  358. {
  359. var currentType = typeof(T);
  360. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  361. }
  362. /// <inheritdoc />
  363. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  364. {
  365. // Convert to list so this isn't executed for each iteration
  366. var parts = GetExportTypes<T>()
  367. .Select(CreateInstanceSafe)
  368. .Where(i => i != null)
  369. .Cast<T>()
  370. .ToList();
  371. if (manageLifetime)
  372. {
  373. lock (_disposableParts)
  374. {
  375. _disposableParts.AddRange(parts.OfType<IDisposable>());
  376. }
  377. }
  378. return parts;
  379. }
  380. /// <summary>
  381. /// Runs the startup tasks.
  382. /// </summary>
  383. /// <returns><see cref="Task" />.</returns>
  384. public async Task RunStartupTasksAsync()
  385. {
  386. Logger.LogInformation("Running startup tasks");
  387. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  388. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  389. _mediaEncoder.SetFFmpegPath();
  390. Logger.LogInformation("ServerId: {0}", SystemId);
  391. var entryPoints = GetExports<IServerEntryPoint>();
  392. var stopWatch = new Stopwatch();
  393. stopWatch.Start();
  394. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  395. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  396. Logger.LogInformation("Core startup complete");
  397. CoreStartupHasCompleted = true;
  398. stopWatch.Restart();
  399. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  400. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  401. stopWatch.Stop();
  402. }
  403. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  404. {
  405. foreach (var entryPoint in entryPoints)
  406. {
  407. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  408. {
  409. continue;
  410. }
  411. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  412. yield return entryPoint.RunAsync();
  413. }
  414. }
  415. /// <inheritdoc/>
  416. public void Init()
  417. {
  418. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  419. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  420. // Safeguard against invalid configuration
  421. if (HttpPort == HttpsPort)
  422. {
  423. HttpPort = ServerConfiguration.DefaultHttpPort;
  424. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  425. }
  426. if (Plugins != null)
  427. {
  428. var pluginBuilder = new StringBuilder();
  429. foreach (var plugin in Plugins)
  430. {
  431. pluginBuilder.Append(plugin.Name)
  432. .Append(' ')
  433. .Append(plugin.Version)
  434. .AppendLine();
  435. }
  436. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  437. }
  438. DiscoverTypes();
  439. RegisterServices();
  440. }
  441. /// <summary>
  442. /// Registers services/resources with the service collection that will be available via DI.
  443. /// </summary>
  444. protected virtual void RegisterServices()
  445. {
  446. ServiceCollection.AddSingleton(_startupOptions);
  447. ServiceCollection.AddMemoryCache();
  448. ServiceCollection.AddSingleton(ConfigurationManager);
  449. ServiceCollection.AddSingleton<IApplicationHost>(this);
  450. ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  451. ServiceCollection.AddSingleton<IJsonSerializer, JsonSerializer>();
  452. ServiceCollection.AddSingleton(_fileSystemManager);
  453. ServiceCollection.AddSingleton<TvdbClientManager>();
  454. ServiceCollection.AddSingleton<TmdbClientManager>();
  455. ServiceCollection.AddSingleton(_networkManager);
  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. _webSocketManager = Resolve<IWebSocketManager>();
  534. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  535. SetStaticProperties();
  536. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  537. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  538. FindParts();
  539. }
  540. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  541. {
  542. // Distinct these to prevent users from reporting problems that aren't actually problems
  543. var commandLineArgs = Environment
  544. .GetCommandLineArgs()
  545. .Distinct();
  546. // Get all relevant environment variables
  547. var allEnvVars = Environment.GetEnvironmentVariables();
  548. var relevantEnvVars = new Dictionary<object, object>();
  549. foreach (var key in allEnvVars.Keys)
  550. {
  551. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  552. {
  553. relevantEnvVars.Add(key, allEnvVars[key]);
  554. }
  555. }
  556. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  557. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  558. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  559. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  560. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  561. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  562. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  563. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  564. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  565. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  566. }
  567. private X509Certificate2 GetCertificate(CertificateInfo info)
  568. {
  569. var certificateLocation = info?.Path;
  570. if (string.IsNullOrWhiteSpace(certificateLocation))
  571. {
  572. return null;
  573. }
  574. try
  575. {
  576. if (!File.Exists(certificateLocation))
  577. {
  578. return null;
  579. }
  580. // Don't use an empty string password
  581. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  582. var localCert = new X509Certificate2(certificateLocation, password);
  583. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  584. if (!localCert.HasPrivateKey)
  585. {
  586. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  587. return null;
  588. }
  589. return localCert;
  590. }
  591. catch (Exception ex)
  592. {
  593. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  594. return null;
  595. }
  596. }
  597. /// <summary>
  598. /// Dirty hacks.
  599. /// </summary>
  600. private void SetStaticProperties()
  601. {
  602. // For now there's no real way to inject these properly
  603. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  604. BaseItem.ConfigurationManager = ServerConfigurationManager;
  605. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  606. BaseItem.ProviderManager = Resolve<IProviderManager>();
  607. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  608. BaseItem.ItemRepository = Resolve<IItemRepository>();
  609. BaseItem.FileSystem = _fileSystemManager;
  610. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  611. BaseItem.ChannelManager = Resolve<IChannelManager>();
  612. Video.LiveTvManager = Resolve<ILiveTvManager>();
  613. Folder.UserViewManager = Resolve<IUserViewManager>();
  614. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  615. UserView.CollectionManager = Resolve<ICollectionManager>();
  616. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  617. CollectionFolder.XmlSerializer = _xmlSerializer;
  618. CollectionFolder.JsonSerializer = Resolve<IJsonSerializer>();
  619. CollectionFolder.ApplicationHost = this;
  620. }
  621. /// <summary>
  622. /// Finds plugin components and register them with the appropriate services.
  623. /// </summary>
  624. private void FindParts()
  625. {
  626. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  627. {
  628. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  629. ConfigurationManager.SaveConfiguration();
  630. }
  631. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  632. _plugins = GetExports<IPlugin>()
  633. .Select(LoadPlugin)
  634. .Where(i => i != null)
  635. .ToArray();
  636. _urlPrefixes = GetUrlPrefixes().ToArray();
  637. _webSocketManager.Init(GetExports<IWebSocketListener>());
  638. Resolve<ILibraryManager>().AddParts(
  639. GetExports<IResolverIgnoreRule>(),
  640. GetExports<IItemResolver>(),
  641. GetExports<IIntroProvider>(),
  642. GetExports<IBaseItemComparer>(),
  643. GetExports<ILibraryPostScanTask>());
  644. Resolve<IProviderManager>().AddParts(
  645. GetExports<IImageProvider>(),
  646. GetExports<IMetadataService>(),
  647. GetExports<IMetadataProvider>(),
  648. GetExports<IMetadataSaver>(),
  649. GetExports<IExternalId>());
  650. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  651. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  652. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  653. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  654. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  655. Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>());
  656. }
  657. private IPlugin LoadPlugin(IPlugin plugin)
  658. {
  659. try
  660. {
  661. plugin.RegisterServices(ServiceCollection);
  662. }
  663. catch (Exception ex)
  664. {
  665. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  666. return null;
  667. }
  668. return plugin;
  669. }
  670. /// <summary>
  671. /// Discovers the types.
  672. /// </summary>
  673. protected void DiscoverTypes()
  674. {
  675. Logger.LogInformation("Loading assemblies");
  676. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  677. }
  678. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  679. {
  680. foreach (var ass in assemblies)
  681. {
  682. Type[] exportedTypes;
  683. try
  684. {
  685. exportedTypes = ass.GetExportedTypes();
  686. }
  687. catch (FileNotFoundException ex)
  688. {
  689. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  690. continue;
  691. }
  692. catch (TypeLoadException ex)
  693. {
  694. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  695. continue;
  696. }
  697. foreach (Type type in exportedTypes)
  698. {
  699. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  700. {
  701. yield return type;
  702. }
  703. }
  704. }
  705. }
  706. private CertificateInfo CertificateInfo { get; set; }
  707. public X509Certificate2 Certificate { get; private set; }
  708. private IEnumerable<string> GetUrlPrefixes()
  709. {
  710. var hosts = new[] { "+" };
  711. return hosts.SelectMany(i =>
  712. {
  713. var prefixes = new List<string>
  714. {
  715. "http://" + i + ":" + HttpPort + "/"
  716. };
  717. if (CertificateInfo != null)
  718. {
  719. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  720. }
  721. return prefixes;
  722. });
  723. }
  724. /// <summary>
  725. /// Called when [configuration updated].
  726. /// </summary>
  727. /// <param name="sender">The sender.</param>
  728. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  729. protected void OnConfigurationUpdated(object sender, EventArgs e)
  730. {
  731. var requiresRestart = false;
  732. // Don't do anything if these haven't been set yet
  733. if (HttpPort != 0 && HttpsPort != 0)
  734. {
  735. // Need to restart if ports have changed
  736. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  737. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  738. {
  739. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  740. {
  741. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  742. ServerConfigurationManager.SaveConfiguration();
  743. requiresRestart = true;
  744. }
  745. }
  746. }
  747. if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  748. {
  749. requiresRestart = true;
  750. }
  751. var currentCertPath = CertificateInfo?.Path;
  752. var newCertPath = ServerConfigurationManager.Configuration.CertificatePath;
  753. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  754. {
  755. requiresRestart = true;
  756. }
  757. if (requiresRestart)
  758. {
  759. Logger.LogInformation("App needs to be restarted due to configuration change.");
  760. NotifyPendingRestart();
  761. }
  762. }
  763. /// <summary>
  764. /// Notifies that the kernel that a change has been made that requires a restart.
  765. /// </summary>
  766. public void NotifyPendingRestart()
  767. {
  768. Logger.LogInformation("App needs to be restarted.");
  769. var changed = !HasPendingRestart;
  770. HasPendingRestart = true;
  771. if (changed)
  772. {
  773. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  774. }
  775. }
  776. /// <summary>
  777. /// Restarts this instance.
  778. /// </summary>
  779. public void Restart()
  780. {
  781. if (!CanSelfRestart)
  782. {
  783. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  784. }
  785. if (IsShuttingDown)
  786. {
  787. return;
  788. }
  789. IsShuttingDown = true;
  790. Task.Run(async () =>
  791. {
  792. try
  793. {
  794. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  795. }
  796. catch (Exception ex)
  797. {
  798. Logger.LogError(ex, "Error sending server restart notification");
  799. }
  800. Logger.LogInformation("Calling RestartInternal");
  801. RestartInternal();
  802. });
  803. }
  804. protected abstract void RestartInternal();
  805. /// <summary>
  806. /// Comparison function used in <see cref="GetPlugins" />.
  807. /// </summary>
  808. /// <param name="a">Item to compare.</param>
  809. /// <param name="b">Item to compare with.</param>
  810. /// <returns>Boolean result of the operation.</returns>
  811. private static int VersionCompare(
  812. (Version PluginVersion, string Name, string Path) a,
  813. (Version PluginVersion, string Name, string Path) b)
  814. {
  815. int compare = string.Compare(a.Name, b.Name, true, CultureInfo.InvariantCulture);
  816. if (compare == 0)
  817. {
  818. return a.PluginVersion.CompareTo(b.PluginVersion);
  819. }
  820. return compare;
  821. }
  822. /// <summary>
  823. /// Returns a list of plugins to install.
  824. /// </summary>
  825. /// <param name="path">Path to check.</param>
  826. /// <param name="cleanup">True if an attempt should be made to delete old plugs.</param>
  827. /// <returns>Enumerable list of dlls to load.</returns>
  828. private IEnumerable<string> GetPlugins(string path, bool cleanup = true)
  829. {
  830. var dllList = new List<string>();
  831. var versions = new List<(Version PluginVersion, string Name, string Path)>();
  832. var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly);
  833. string metafile;
  834. foreach (var dir in directories)
  835. {
  836. try
  837. {
  838. metafile = Path.Combine(dir, "meta.json");
  839. if (File.Exists(metafile))
  840. {
  841. var manifest = _jsonSerializer.DeserializeFromFile<PluginManifest>(metafile);
  842. if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
  843. {
  844. targetAbi = new Version(0, 0, 0, 1);
  845. }
  846. if (!Version.TryParse(manifest.Version, out var version))
  847. {
  848. version = new Version(0, 0, 0, 1);
  849. }
  850. if (ApplicationVersion >= targetAbi)
  851. {
  852. // Only load Plugins if the plugin is built for this version or below.
  853. versions.Add((version, manifest.Name, dir));
  854. }
  855. }
  856. else
  857. {
  858. // No metafile, so lets see if the folder is versioned.
  859. metafile = dir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)[^1];
  860. int versionIndex = dir.LastIndexOf('_');
  861. if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version ver))
  862. {
  863. // Versioned folder.
  864. versions.Add((ver, metafile, dir));
  865. }
  866. else
  867. {
  868. // Un-versioned folder - Add it under the path name and version 0.0.0.1.
  869. versions.Add((new Version(0, 0, 0, 1), metafile, dir));
  870. }
  871. }
  872. }
  873. catch
  874. {
  875. continue;
  876. }
  877. }
  878. string lastName = string.Empty;
  879. versions.Sort(VersionCompare);
  880. // Traverse backwards through the list.
  881. // The first item will be the latest version.
  882. for (int x = versions.Count - 1; x >= 0; x--)
  883. {
  884. if (!string.Equals(lastName, versions[x].Name, StringComparison.OrdinalIgnoreCase))
  885. {
  886. dllList.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories));
  887. lastName = versions[x].Name;
  888. continue;
  889. }
  890. if (!string.IsNullOrEmpty(lastName) && cleanup)
  891. {
  892. // Attempt a cleanup of old folders.
  893. try
  894. {
  895. Logger.LogDebug("Deleting {Path}", versions[x].Path);
  896. Directory.Delete(versions[x].Path, true);
  897. }
  898. catch (Exception e)
  899. {
  900. Logger.LogWarning(e, "Unable to delete {Path}", versions[x].Path);
  901. }
  902. }
  903. }
  904. return dllList;
  905. }
  906. /// <summary>
  907. /// Gets the composable part assemblies.
  908. /// </summary>
  909. /// <returns>IEnumerable{Assembly}.</returns>
  910. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  911. {
  912. if (Directory.Exists(ApplicationPaths.PluginsPath))
  913. {
  914. foreach (var file in GetPlugins(ApplicationPaths.PluginsPath))
  915. {
  916. Assembly plugAss;
  917. try
  918. {
  919. plugAss = Assembly.LoadFrom(file);
  920. }
  921. catch (FileLoadException ex)
  922. {
  923. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  924. continue;
  925. }
  926. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  927. yield return plugAss;
  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. 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="cancellationToken">The cancellation token.</param>
  962. /// <returns>SystemInfo.</returns>
  963. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  964. {
  965. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  966. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  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 = transcodingTempPath,
  987. ServerName = FriendlyName,
  988. LocalAddress = localAddress,
  989. SupportsLibraryMonitor = true,
  990. EncoderLocation = _mediaEncoder.EncoderLocation,
  991. SystemArchitecture = RuntimeInformation.OSArchitecture,
  992. PackageName = _startupOptions.PackageName
  993. };
  994. }
  995. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  996. => _networkManager.GetMacAddresses()
  997. .Select(i => new WakeOnLanInfo(i))
  998. .ToList();
  999. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1000. {
  1001. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1002. return new PublicSystemInfo
  1003. {
  1004. Version = ApplicationVersionString,
  1005. ProductName = ApplicationProductName,
  1006. Id = SystemId,
  1007. OperatingSystem = OperatingSystem.Id.ToString(),
  1008. ServerName = FriendlyName,
  1009. LocalAddress = localAddress,
  1010. StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
  1011. };
  1012. }
  1013. /// <inheritdoc/>
  1014. public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.Configuration.EnableHttps;
  1015. /// <inheritdoc/>
  1016. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1017. {
  1018. try
  1019. {
  1020. // Return the first matched address, if found, or the first known local address
  1021. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1022. if (addresses.Count == 0)
  1023. {
  1024. return null;
  1025. }
  1026. return GetLocalApiUrl(addresses[0]);
  1027. }
  1028. catch (Exception ex)
  1029. {
  1030. Logger.LogError(ex, "Error getting local Ip address information");
  1031. }
  1032. return null;
  1033. }
  1034. /// <summary>
  1035. /// Removes the scope id from IPv6 addresses.
  1036. /// </summary>
  1037. /// <param name="address">The IPv6 address.</param>
  1038. /// <returns>The IPv6 address without the scope id.</returns>
  1039. private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
  1040. {
  1041. var index = address.IndexOf('%');
  1042. if (index == -1)
  1043. {
  1044. return address;
  1045. }
  1046. return address.Slice(0, index);
  1047. }
  1048. /// <inheritdoc />
  1049. public string GetLocalApiUrl(IPAddress ipAddress)
  1050. {
  1051. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1052. {
  1053. var str = RemoveScopeId(ipAddress.ToString());
  1054. Span<char> span = new char[str.Length + 2];
  1055. span[0] = '[';
  1056. str.CopyTo(span.Slice(1));
  1057. span[^1] = ']';
  1058. return GetLocalApiUrl(span);
  1059. }
  1060. return GetLocalApiUrl(ipAddress.ToString());
  1061. }
  1062. /// <inheritdoc/>
  1063. public string GetLoopbackHttpApiUrl()
  1064. {
  1065. return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
  1066. }
  1067. /// <inheritdoc/>
  1068. public string GetLocalApiUrl(ReadOnlySpan<char> host, string scheme = null, int? port = null)
  1069. {
  1070. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  1071. // not. For consistency, always trim the trailing slash.
  1072. return new UriBuilder
  1073. {
  1074. Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
  1075. Host = host.ToString(),
  1076. Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
  1077. Path = ServerConfigurationManager.Configuration.BaseUrl
  1078. }.ToString().TrimEnd('/');
  1079. }
  1080. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1081. {
  1082. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1083. }
  1084. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1085. {
  1086. var addresses = ServerConfigurationManager
  1087. .Configuration
  1088. .LocalNetworkAddresses
  1089. .Select(x => NormalizeConfiguredLocalAddress(x))
  1090. .Where(i => i != null)
  1091. .ToList();
  1092. if (addresses.Count == 0)
  1093. {
  1094. addresses.AddRange(_networkManager.GetLocalIpAddresses());
  1095. }
  1096. var resultList = new List<IPAddress>();
  1097. foreach (var address in addresses)
  1098. {
  1099. if (!allowLoopback)
  1100. {
  1101. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1102. {
  1103. continue;
  1104. }
  1105. }
  1106. if (await IsLocalIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false))
  1107. {
  1108. resultList.Add(address);
  1109. if (limit > 0 && resultList.Count >= limit)
  1110. {
  1111. return resultList;
  1112. }
  1113. }
  1114. }
  1115. return resultList;
  1116. }
  1117. public IPAddress NormalizeConfiguredLocalAddress(ReadOnlySpan<char> address)
  1118. {
  1119. var index = address.Trim('/').IndexOf('/');
  1120. if (index != -1)
  1121. {
  1122. address = address.Slice(index + 1);
  1123. }
  1124. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1125. {
  1126. return result;
  1127. }
  1128. return null;
  1129. }
  1130. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1131. private async Task<bool> IsLocalIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1132. {
  1133. if (address.Equals(IPAddress.Loopback)
  1134. || address.Equals(IPAddress.IPv6Loopback))
  1135. {
  1136. return true;
  1137. }
  1138. var apiUrl = GetLocalApiUrl(address) + "/system/ping";
  1139. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1140. {
  1141. return cachedResult;
  1142. }
  1143. try
  1144. {
  1145. using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl);
  1146. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  1147. .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
  1148. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  1149. var result = await System.Text.Json.JsonSerializer.DeserializeAsync<string>(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false);
  1150. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1151. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1152. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1153. return valid;
  1154. }
  1155. catch (OperationCanceledException)
  1156. {
  1157. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1158. throw;
  1159. }
  1160. catch (Exception ex)
  1161. {
  1162. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1163. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1164. return false;
  1165. }
  1166. }
  1167. public string FriendlyName =>
  1168. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1169. ? Environment.MachineName
  1170. : ServerConfigurationManager.Configuration.ServerName;
  1171. /// <summary>
  1172. /// Shuts down.
  1173. /// </summary>
  1174. public async Task Shutdown()
  1175. {
  1176. if (IsShuttingDown)
  1177. {
  1178. return;
  1179. }
  1180. IsShuttingDown = true;
  1181. try
  1182. {
  1183. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1184. }
  1185. catch (Exception ex)
  1186. {
  1187. Logger.LogError(ex, "Error sending server shutdown notification");
  1188. }
  1189. ShutdownInternal();
  1190. }
  1191. protected abstract void ShutdownInternal();
  1192. public event EventHandler HasUpdateAvailableChanged;
  1193. private bool _hasUpdateAvailable;
  1194. public bool HasUpdateAvailable
  1195. {
  1196. get => _hasUpdateAvailable;
  1197. set
  1198. {
  1199. var fireEvent = value && !_hasUpdateAvailable;
  1200. _hasUpdateAvailable = value;
  1201. if (fireEvent)
  1202. {
  1203. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1204. }
  1205. }
  1206. }
  1207. /// <summary>
  1208. /// Removes the plugin.
  1209. /// </summary>
  1210. /// <param name="plugin">The plugin.</param>
  1211. public void RemovePlugin(IPlugin plugin)
  1212. {
  1213. var list = _plugins.ToList();
  1214. list.Remove(plugin);
  1215. _plugins = list.ToArray();
  1216. }
  1217. public IEnumerable<Assembly> GetApiPluginAssemblies()
  1218. {
  1219. var assemblies = _allConcreteTypes
  1220. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  1221. .Select(i => i.Assembly)
  1222. .Distinct();
  1223. foreach (var assembly in assemblies)
  1224. {
  1225. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  1226. yield return assembly;
  1227. }
  1228. }
  1229. public virtual void LaunchUrl(string url)
  1230. {
  1231. if (!CanLaunchWebBrowser)
  1232. {
  1233. throw new NotSupportedException();
  1234. }
  1235. var process = new Process
  1236. {
  1237. StartInfo = new ProcessStartInfo
  1238. {
  1239. FileName = url,
  1240. UseShellExecute = true,
  1241. ErrorDialog = false
  1242. },
  1243. EnableRaisingEvents = true
  1244. };
  1245. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1246. try
  1247. {
  1248. process.Start();
  1249. }
  1250. catch (Exception ex)
  1251. {
  1252. Logger.LogError(ex, "Error launching url: {url}", url);
  1253. throw;
  1254. }
  1255. }
  1256. private bool _disposed = false;
  1257. /// <summary>
  1258. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1259. /// </summary>
  1260. public void Dispose()
  1261. {
  1262. Dispose(true);
  1263. GC.SuppressFinalize(this);
  1264. }
  1265. /// <summary>
  1266. /// Releases unmanaged and - optionally - managed resources.
  1267. /// </summary>
  1268. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1269. protected virtual void Dispose(bool dispose)
  1270. {
  1271. if (_disposed)
  1272. {
  1273. return;
  1274. }
  1275. if (dispose)
  1276. {
  1277. var type = GetType();
  1278. Logger.LogInformation("Disposing {Type}", type.Name);
  1279. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1280. _disposableParts.Clear();
  1281. foreach (var part in parts)
  1282. {
  1283. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1284. try
  1285. {
  1286. part.Dispose();
  1287. }
  1288. catch (Exception ex)
  1289. {
  1290. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1291. }
  1292. }
  1293. }
  1294. _disposed = true;
  1295. }
  1296. }
  1297. internal class CertificateInfo
  1298. {
  1299. public string Path { get; set; }
  1300. public string Password { get; set; }
  1301. }
  1302. }