ApplicationHost.cs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588
  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.Subtitles;
  100. using MediaBrowser.XbmcMetadata.Providers;
  101. using Microsoft.AspNetCore.Mvc;
  102. using Microsoft.Extensions.DependencyInjection;
  103. using Microsoft.Extensions.Logging;
  104. using Prometheus.DotNetRuntime;
  105. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  106. using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
  107. namespace Emby.Server.Implementations
  108. {
  109. /// <summary>
  110. /// Class CompositionRoot.
  111. /// </summary>
  112. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  113. {
  114. /// <summary>
  115. /// The environment variable prefixes to log at server startup.
  116. /// </summary>
  117. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  118. private readonly IFileSystem _fileSystemManager;
  119. private readonly INetworkManager _networkManager;
  120. private readonly IXmlSerializer _xmlSerializer;
  121. private readonly IStartupOptions _startupOptions;
  122. private IMediaEncoder _mediaEncoder;
  123. private ISessionManager _sessionManager;
  124. private IHttpClientFactory _httpClientFactory;
  125. private IWebSocketManager _webSocketManager;
  126. private string[] _urlPrefixes;
  127. /// <summary>
  128. /// Gets a value indicating whether this instance can self restart.
  129. /// </summary>
  130. public bool CanSelfRestart => _startupOptions.RestartPath != null;
  131. public bool CoreStartupHasCompleted { get; private set; }
  132. public virtual bool CanLaunchWebBrowser
  133. {
  134. get
  135. {
  136. if (!Environment.UserInteractive)
  137. {
  138. return false;
  139. }
  140. if (_startupOptions.IsService)
  141. {
  142. return false;
  143. }
  144. if (OperatingSystem.Id == OperatingSystemId.Windows
  145. || OperatingSystem.Id == OperatingSystemId.Darwin)
  146. {
  147. return true;
  148. }
  149. return false;
  150. }
  151. }
  152. /// <summary>
  153. /// Occurs when [has pending restart changed].
  154. /// </summary>
  155. public event EventHandler HasPendingRestartChanged;
  156. /// <summary>
  157. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  158. /// </summary>
  159. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  160. public bool HasPendingRestart { get; private set; }
  161. /// <inheritdoc />
  162. public bool IsShuttingDown { get; private set; }
  163. /// <summary>
  164. /// Gets the logger.
  165. /// </summary>
  166. protected ILogger<ApplicationHost> Logger { get; }
  167. protected IServiceCollection ServiceCollection { get; }
  168. private IPlugin[] _plugins;
  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 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. public ApplicationHost(
  218. IServerApplicationPaths applicationPaths,
  219. ILoggerFactory loggerFactory,
  220. IStartupOptions options,
  221. IFileSystem fileSystem,
  222. INetworkManager networkManager,
  223. IServiceCollection serviceCollection)
  224. {
  225. _xmlSerializer = new MyXmlSerializer();
  226. ServiceCollection = serviceCollection;
  227. _networkManager = networkManager;
  228. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  229. ApplicationPaths = applicationPaths;
  230. LoggerFactory = loggerFactory;
  231. _fileSystemManager = fileSystem;
  232. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
  233. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  234. _startupOptions = options;
  235. // Initialize runtime stat collection
  236. if (ServerConfigurationManager.Configuration.EnableMetrics)
  237. {
  238. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  239. }
  240. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  241. _networkManager.NetworkChanged += OnNetworkChanged;
  242. CertificateInfo = new CertificateInfo
  243. {
  244. Path = ServerConfigurationManager.Configuration.CertificatePath,
  245. Password = ServerConfigurationManager.Configuration.CertificatePassword
  246. };
  247. Certificate = GetCertificate(CertificateInfo);
  248. ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
  249. ApplicationVersionString = ApplicationVersion.ToString(3);
  250. ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  251. }
  252. public string ExpandVirtualPath(string path)
  253. {
  254. var appPaths = ApplicationPaths;
  255. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  256. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  257. }
  258. public string ReverseVirtualPath(string path)
  259. {
  260. var appPaths = ApplicationPaths;
  261. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  262. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  263. }
  264. private string[] GetConfiguredLocalSubnets()
  265. {
  266. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  267. }
  268. private void OnNetworkChanged(object sender, EventArgs e)
  269. {
  270. _validAddressResults.Clear();
  271. }
  272. /// <inheritdoc />
  273. public Version ApplicationVersion { get; }
  274. /// <inheritdoc />
  275. public string ApplicationVersionString { get; }
  276. /// <summary>
  277. /// Gets the current application user agent.
  278. /// </summary>
  279. /// <value>The application user agent.</value>
  280. public string ApplicationUserAgent { get; }
  281. /// <summary>
  282. /// Gets the email address for use within a comment section of a user agent field.
  283. /// Presently used to provide contact information to MusicBrainz service.
  284. /// </summary>
  285. public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
  286. /// <summary>
  287. /// Gets the current application name.
  288. /// </summary>
  289. /// <value>The application name.</value>
  290. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  291. private DeviceId _deviceId;
  292. public string SystemId
  293. {
  294. get
  295. {
  296. if (_deviceId == null)
  297. {
  298. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  299. }
  300. return _deviceId.Value;
  301. }
  302. }
  303. /// <inheritdoc/>
  304. public string Name => ApplicationProductName;
  305. /// <summary>
  306. /// Creates an instance of type and resolves all constructor dependencies.
  307. /// </summary>
  308. /// <param name="type">The type.</param>
  309. /// <returns>System.Object.</returns>
  310. public object CreateInstance(Type type)
  311. => ActivatorUtilities.CreateInstance(ServiceProvider, type);
  312. /// <summary>
  313. /// Creates an instance of type and resolves all constructor dependencies.
  314. /// </summary>
  315. /// /// <typeparam name="T">The type.</typeparam>
  316. /// <returns>T.</returns>
  317. public T CreateInstance<T>()
  318. => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
  319. /// <summary>
  320. /// Creates the instance safe.
  321. /// </summary>
  322. /// <param name="type">The type.</param>
  323. /// <returns>System.Object.</returns>
  324. protected object CreateInstanceSafe(Type type)
  325. {
  326. try
  327. {
  328. Logger.LogDebug("Creating instance of {Type}", type);
  329. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  330. }
  331. catch (Exception ex)
  332. {
  333. Logger.LogError(ex, "Error creating {Type}", type);
  334. return null;
  335. }
  336. }
  337. /// <summary>
  338. /// Resolves this instance.
  339. /// </summary>
  340. /// <typeparam name="T">The type</typeparam>
  341. /// <returns>``0.</returns>
  342. public T Resolve<T>() => ServiceProvider.GetService<T>();
  343. /// <summary>
  344. /// Gets the export types.
  345. /// </summary>
  346. /// <typeparam name="T">The type.</typeparam>
  347. /// <returns>IEnumerable{Type}.</returns>
  348. public IEnumerable<Type> GetExportTypes<T>()
  349. {
  350. var currentType = typeof(T);
  351. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  352. }
  353. /// <inheritdoc />
  354. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  355. {
  356. // Convert to list so this isn't executed for each iteration
  357. var parts = GetExportTypes<T>()
  358. .Select(CreateInstanceSafe)
  359. .Where(i => i != null)
  360. .Cast<T>()
  361. .ToList();
  362. if (manageLifetime)
  363. {
  364. lock (_disposableParts)
  365. {
  366. _disposableParts.AddRange(parts.OfType<IDisposable>());
  367. }
  368. }
  369. return parts;
  370. }
  371. /// <summary>
  372. /// Runs the startup tasks.
  373. /// </summary>
  374. /// <returns><see cref="Task" />.</returns>
  375. public async Task RunStartupTasksAsync()
  376. {
  377. Logger.LogInformation("Running startup tasks");
  378. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  379. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  380. _mediaEncoder.SetFFmpegPath();
  381. Logger.LogInformation("ServerId: {0}", SystemId);
  382. var entryPoints = GetExports<IServerEntryPoint>();
  383. var stopWatch = new Stopwatch();
  384. stopWatch.Start();
  385. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  386. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  387. Logger.LogInformation("Core startup complete");
  388. CoreStartupHasCompleted = true;
  389. stopWatch.Restart();
  390. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  391. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  392. stopWatch.Stop();
  393. }
  394. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  395. {
  396. foreach (var entryPoint in entryPoints)
  397. {
  398. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  399. {
  400. continue;
  401. }
  402. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  403. yield return entryPoint.RunAsync();
  404. }
  405. }
  406. /// <inheritdoc/>
  407. public void Init()
  408. {
  409. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  410. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  411. // Safeguard against invalid configuration
  412. if (HttpPort == HttpsPort)
  413. {
  414. HttpPort = ServerConfiguration.DefaultHttpPort;
  415. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  416. }
  417. if (Plugins != null)
  418. {
  419. var pluginBuilder = new StringBuilder();
  420. foreach (var plugin in Plugins)
  421. {
  422. pluginBuilder.Append(plugin.Name)
  423. .Append(' ')
  424. .Append(plugin.Version)
  425. .AppendLine();
  426. }
  427. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  428. }
  429. DiscoverTypes();
  430. RegisterServices();
  431. }
  432. /// <summary>
  433. /// Registers services/resources with the service collection that will be available via DI.
  434. /// </summary>
  435. protected virtual void RegisterServices()
  436. {
  437. ServiceCollection.AddSingleton(_startupOptions);
  438. ServiceCollection.AddMemoryCache();
  439. ServiceCollection.AddSingleton(ConfigurationManager);
  440. ServiceCollection.AddSingleton<IApplicationHost>(this);
  441. ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  442. ServiceCollection.AddSingleton<IJsonSerializer, JsonSerializer>();
  443. ServiceCollection.AddSingleton(_fileSystemManager);
  444. ServiceCollection.AddSingleton<TvdbClientManager>();
  445. ServiceCollection.AddSingleton(_networkManager);
  446. ServiceCollection.AddSingleton<IIsoManager, IsoManager>();
  447. ServiceCollection.AddSingleton<ITaskManager, TaskManager>();
  448. ServiceCollection.AddSingleton(_xmlSerializer);
  449. ServiceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  450. ServiceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  451. ServiceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  452. ServiceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  453. ServiceCollection.AddSingleton<IZipClient, ZipClient>();
  454. ServiceCollection.AddSingleton<IServerApplicationHost>(this);
  455. ServiceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  456. ServiceCollection.AddSingleton(ServerConfigurationManager);
  457. ServiceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  458. ServiceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  459. ServiceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  460. ServiceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  461. ServiceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  462. ServiceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  463. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  464. ServiceCollection.AddTransient(provider => new Lazy<IDtoService>(provider.GetRequiredService<IDtoService>));
  465. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  466. ServiceCollection.AddTransient(provider => new Lazy<EncodingHelper>(provider.GetRequiredService<EncodingHelper>));
  467. ServiceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  468. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  469. ServiceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  470. ServiceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  471. ServiceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  472. ServiceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  473. ServiceCollection.AddSingleton<IMusicManager, MusicManager>();
  474. ServiceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  475. ServiceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  476. ServiceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  477. ServiceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  478. ServiceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  479. ServiceCollection.AddSingleton<IDeviceManager, DeviceManager>();
  480. ServiceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  481. ServiceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  482. ServiceCollection.AddSingleton<IProviderManager, ProviderManager>();
  483. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  484. ServiceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  485. ServiceCollection.AddSingleton<IDtoService, DtoService>();
  486. ServiceCollection.AddSingleton<IChannelManager, ChannelManager>();
  487. ServiceCollection.AddSingleton<ISessionManager, SessionManager>();
  488. ServiceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  489. ServiceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  490. ServiceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  491. ServiceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  492. ServiceCollection.AddSingleton<LiveTvDtoService>();
  493. ServiceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  494. ServiceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  495. ServiceCollection.AddSingleton<INotificationManager, NotificationManager>();
  496. ServiceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  497. ServiceCollection.AddSingleton<IChapterManager, ChapterManager>();
  498. ServiceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  499. ServiceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  500. ServiceCollection.AddSingleton<ISessionContext, SessionContext>();
  501. ServiceCollection.AddSingleton<IAuthService, AuthService>();
  502. ServiceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  503. ServiceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  504. ServiceCollection.AddSingleton<IResourceFileManager, ResourceFileManager>();
  505. ServiceCollection.AddSingleton<EncodingHelper>();
  506. ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  507. ServiceCollection.AddSingleton<TranscodingJobHelper>();
  508. ServiceCollection.AddScoped<MediaInfoHelper>();
  509. ServiceCollection.AddScoped<AudioHelper>();
  510. ServiceCollection.AddScoped<DynamicHlsHelper>();
  511. }
  512. /// <summary>
  513. /// Create services registered with the service container that need to be initialized at application startup.
  514. /// </summary>
  515. /// <returns>A task representing the service initialization operation.</returns>
  516. public async Task InitializeServices()
  517. {
  518. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  519. await localizationManager.LoadAll().ConfigureAwait(false);
  520. _mediaEncoder = Resolve<IMediaEncoder>();
  521. _sessionManager = Resolve<ISessionManager>();
  522. _httpClientFactory = Resolve<IHttpClientFactory>();
  523. _webSocketManager = Resolve<IWebSocketManager>();
  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. .Select(LoadPlugin)
  624. .Where(i => i != null)
  625. .ToArray();
  626. _urlPrefixes = GetUrlPrefixes().ToArray();
  627. _webSocketManager.Init(GetExports<IWebSocketListener>());
  628. Resolve<ILibraryManager>().AddParts(
  629. GetExports<IResolverIgnoreRule>(),
  630. GetExports<IItemResolver>(),
  631. GetExports<IIntroProvider>(),
  632. GetExports<IBaseItemComparer>(),
  633. GetExports<ILibraryPostScanTask>());
  634. Resolve<IProviderManager>().AddParts(
  635. GetExports<IImageProvider>(),
  636. GetExports<IMetadataService>(),
  637. GetExports<IMetadataProvider>(),
  638. GetExports<IMetadataSaver>(),
  639. GetExports<IExternalId>());
  640. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  641. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  642. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  643. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  644. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  645. Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>());
  646. }
  647. private IPlugin LoadPlugin(IPlugin plugin)
  648. {
  649. try
  650. {
  651. if (plugin is IPluginAssembly assemblyPlugin)
  652. {
  653. var assembly = plugin.GetType().Assembly;
  654. var assemblyName = assembly.GetName();
  655. var assemblyFilePath = assembly.Location;
  656. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  657. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  658. try
  659. {
  660. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  661. if (idAttributes.Length > 0)
  662. {
  663. var attribute = (GuidAttribute)idAttributes[0];
  664. var assemblyId = new Guid(attribute.Value);
  665. assemblyPlugin.SetId(assemblyId);
  666. }
  667. }
  668. catch (Exception ex)
  669. {
  670. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  671. }
  672. }
  673. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  674. {
  675. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  676. }
  677. plugin.RegisterServices(ServiceCollection);
  678. }
  679. catch (Exception ex)
  680. {
  681. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  682. return null;
  683. }
  684. return plugin;
  685. }
  686. /// <summary>
  687. /// Discovers the types.
  688. /// </summary>
  689. protected void DiscoverTypes()
  690. {
  691. Logger.LogInformation("Loading assemblies");
  692. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  693. }
  694. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  695. {
  696. foreach (var ass in assemblies)
  697. {
  698. Type[] exportedTypes;
  699. try
  700. {
  701. exportedTypes = ass.GetExportedTypes();
  702. }
  703. catch (FileNotFoundException ex)
  704. {
  705. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  706. continue;
  707. }
  708. catch (TypeLoadException ex)
  709. {
  710. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  711. continue;
  712. }
  713. foreach (Type type in exportedTypes)
  714. {
  715. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  716. {
  717. yield return type;
  718. }
  719. }
  720. }
  721. }
  722. private CertificateInfo CertificateInfo { get; set; }
  723. public X509Certificate2 Certificate { get; private set; }
  724. private IEnumerable<string> GetUrlPrefixes()
  725. {
  726. var hosts = new[] { "+" };
  727. return hosts.SelectMany(i =>
  728. {
  729. var prefixes = new List<string>
  730. {
  731. "http://" + i + ":" + HttpPort + "/"
  732. };
  733. if (CertificateInfo != null)
  734. {
  735. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  736. }
  737. return prefixes;
  738. });
  739. }
  740. /// <summary>
  741. /// Called when [configuration updated].
  742. /// </summary>
  743. /// <param name="sender">The sender.</param>
  744. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  745. protected void OnConfigurationUpdated(object sender, EventArgs e)
  746. {
  747. var requiresRestart = false;
  748. // Don't do anything if these haven't been set yet
  749. if (HttpPort != 0 && HttpsPort != 0)
  750. {
  751. // Need to restart if ports have changed
  752. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  753. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  754. {
  755. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  756. {
  757. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  758. ServerConfigurationManager.SaveConfiguration();
  759. requiresRestart = true;
  760. }
  761. }
  762. }
  763. if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  764. {
  765. requiresRestart = true;
  766. }
  767. var currentCertPath = CertificateInfo?.Path;
  768. var newCertPath = ServerConfigurationManager.Configuration.CertificatePath;
  769. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  770. {
  771. requiresRestart = true;
  772. }
  773. if (requiresRestart)
  774. {
  775. Logger.LogInformation("App needs to be restarted due to configuration change.");
  776. NotifyPendingRestart();
  777. }
  778. }
  779. /// <summary>
  780. /// Notifies that the kernel that a change has been made that requires a restart.
  781. /// </summary>
  782. public void NotifyPendingRestart()
  783. {
  784. Logger.LogInformation("App needs to be restarted.");
  785. var changed = !HasPendingRestart;
  786. HasPendingRestart = true;
  787. if (changed)
  788. {
  789. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  790. }
  791. }
  792. /// <summary>
  793. /// Restarts this instance.
  794. /// </summary>
  795. public void Restart()
  796. {
  797. if (!CanSelfRestart)
  798. {
  799. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  800. }
  801. if (IsShuttingDown)
  802. {
  803. return;
  804. }
  805. IsShuttingDown = true;
  806. Task.Run(async () =>
  807. {
  808. try
  809. {
  810. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  811. }
  812. catch (Exception ex)
  813. {
  814. Logger.LogError(ex, "Error sending server restart notification");
  815. }
  816. Logger.LogInformation("Calling RestartInternal");
  817. RestartInternal();
  818. });
  819. }
  820. protected abstract void RestartInternal();
  821. /// <summary>
  822. /// Comparison function used in <see cref="GetLatestDLLVersion" />.
  823. /// </summary>
  824. /// <param name="a">Item to compare.</param>
  825. /// <param name="b">Item to compare with.</param>
  826. /// <returns>Boolean result of the operation.</returns>
  827. private static int VersionCompare(
  828. (Version PluginVersion, string Name, string Path) a,
  829. (Version PluginVersion, string Name, string Path) b)
  830. {
  831. int compare = string.Compare(a.Name, b.Name, true, CultureInfo.InvariantCulture);
  832. if (compare == 0)
  833. {
  834. return a.PluginVersion.CompareTo(b.PluginVersion);
  835. }
  836. return compare;
  837. }
  838. /// <summary>
  839. /// Returns a list of plugsin to install.
  840. /// </summary>
  841. /// <param name="path">Path to check.</param>
  842. /// <param name="cleanup">True if an attempt should be made to delete old plugs.</param>
  843. /// <returns>Enumerable list of dlls to load.</returns>
  844. private IEnumerable<string> GetPlugins(string path, bool cleanup = true)
  845. {
  846. var dllList = new List<string>();
  847. var versions = new List<(Version PluginVersion, string Name, string Path)>();
  848. var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly);
  849. var serializer = new JsonSerializer();
  850. foreach (var dir in directories)
  851. {
  852. try
  853. {
  854. var manifest = serializer.DeserializeFromFile<PlugInManifest>(dir + "\\meta.json");
  855. if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
  856. {
  857. targetAbi = new Version(0, 0, 0, 1);
  858. }
  859. if (!Version.TryParse(manifest.Version, out var version))
  860. {
  861. version = new Version(0, 0, 0, 1);
  862. }
  863. if (targetAbi <= ApplicationVersion)
  864. {
  865. // Only load Plugins for this version or below.
  866. versions.Add((version, manifest.Name, dir));
  867. }
  868. }
  869. catch
  870. {
  871. continue;
  872. }
  873. }
  874. string lastName = string.Empty;
  875. versions.Sort(VersionCompare);
  876. // Traverse backwards through the list.
  877. // The first item will be the latest version.
  878. for (int x = versions.Count - 1; x >= 0; x--)
  879. {
  880. if (!string.Equals(lastName, versions[x].Name, StringComparison.OrdinalIgnoreCase))
  881. {
  882. dllList.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories));
  883. lastName = versions[x].Name;
  884. continue;
  885. }
  886. if (!string.IsNullOrEmpty(lastName) && cleanup)
  887. {
  888. // Attempt a cleanup of old folders.
  889. try
  890. {
  891. Logger.LogDebug("Deleting {Path}", versions[x].Path);
  892. Directory.Delete(versions[x].Path, true);
  893. }
  894. catch (Exception e)
  895. {
  896. Logger.LogWarning(e, "Unable to delete {Path}", versions[x].Path);
  897. }
  898. }
  899. }
  900. return dllList;
  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. foreach (var file in GetPlugins(ApplicationPaths.PluginsPath))
  911. {
  912. Assembly plugAss;
  913. try
  914. {
  915. plugAss = Assembly.LoadFrom(file);
  916. }
  917. catch (FileLoadException ex)
  918. {
  919. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  920. continue;
  921. }
  922. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  923. yield return plugAss;
  924. }
  925. }
  926. // Include composable parts in the Model assembly
  927. yield return typeof(SystemInfo).Assembly;
  928. // Include composable parts in the Common assembly
  929. yield return typeof(IApplicationHost).Assembly;
  930. // Include composable parts in the Controller assembly
  931. yield return typeof(IServerApplicationHost).Assembly;
  932. // Include composable parts in the Providers assembly
  933. yield return typeof(ProviderUtils).Assembly;
  934. // Include composable parts in the Photos assembly
  935. yield return typeof(PhotoProvider).Assembly;
  936. // Emby.Server implementations
  937. yield return typeof(InstallationManager).Assembly;
  938. // MediaEncoding
  939. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  940. // Dlna
  941. yield return typeof(DlnaEntryPoint).Assembly;
  942. // Local metadata
  943. yield return typeof(BoxSetXmlSaver).Assembly;
  944. // Notifications
  945. yield return typeof(NotificationManager).Assembly;
  946. // Xbmc
  947. yield return typeof(ArtistNfoProvider).Assembly;
  948. foreach (var i in GetAssembliesWithPartsInternal())
  949. {
  950. yield return i;
  951. }
  952. }
  953. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  954. /// <summary>
  955. /// Gets the system status.
  956. /// </summary>
  957. /// <param name="cancellationToken">The cancellation token.</param>
  958. /// <returns>SystemInfo.</returns>
  959. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  960. {
  961. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  962. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  963. return new SystemInfo
  964. {
  965. HasPendingRestart = HasPendingRestart,
  966. IsShuttingDown = IsShuttingDown,
  967. Version = ApplicationVersionString,
  968. WebSocketPortNumber = HttpPort,
  969. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  970. Id = SystemId,
  971. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  972. WebPath = ApplicationPaths.WebPath,
  973. LogPath = ApplicationPaths.LogDirectoryPath,
  974. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  975. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  976. CachePath = ApplicationPaths.CachePath,
  977. OperatingSystem = OperatingSystem.Id.ToString(),
  978. OperatingSystemDisplayName = OperatingSystem.Name,
  979. CanSelfRestart = CanSelfRestart,
  980. CanLaunchWebBrowser = CanLaunchWebBrowser,
  981. HasUpdateAvailable = HasUpdateAvailable,
  982. TranscodingTempPath = transcodingTempPath,
  983. ServerName = FriendlyName,
  984. LocalAddress = localAddress,
  985. SupportsLibraryMonitor = true,
  986. EncoderLocation = _mediaEncoder.EncoderLocation,
  987. SystemArchitecture = RuntimeInformation.OSArchitecture,
  988. PackageName = _startupOptions.PackageName
  989. };
  990. }
  991. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  992. => _networkManager.GetMacAddresses()
  993. .Select(i => new WakeOnLanInfo(i))
  994. .ToList();
  995. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  996. {
  997. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  998. return new PublicSystemInfo
  999. {
  1000. Version = ApplicationVersionString,
  1001. ProductName = ApplicationProductName,
  1002. Id = SystemId,
  1003. OperatingSystem = OperatingSystem.Id.ToString(),
  1004. ServerName = FriendlyName,
  1005. LocalAddress = localAddress
  1006. };
  1007. }
  1008. /// <inheritdoc/>
  1009. public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.Configuration.EnableHttps;
  1010. /// <inheritdoc/>
  1011. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1012. {
  1013. try
  1014. {
  1015. // Return the first matched address, if found, or the first known local address
  1016. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1017. if (addresses.Count == 0)
  1018. {
  1019. return null;
  1020. }
  1021. return GetLocalApiUrl(addresses[0]);
  1022. }
  1023. catch (Exception ex)
  1024. {
  1025. Logger.LogError(ex, "Error getting local Ip address information");
  1026. }
  1027. return null;
  1028. }
  1029. /// <summary>
  1030. /// Removes the scope id from IPv6 addresses.
  1031. /// </summary>
  1032. /// <param name="address">The IPv6 address.</param>
  1033. /// <returns>The IPv6 address without the scope id.</returns>
  1034. private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
  1035. {
  1036. var index = address.IndexOf('%');
  1037. if (index == -1)
  1038. {
  1039. return address;
  1040. }
  1041. return address.Slice(0, index);
  1042. }
  1043. /// <inheritdoc />
  1044. public string GetLocalApiUrl(IPAddress ipAddress)
  1045. {
  1046. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1047. {
  1048. var str = RemoveScopeId(ipAddress.ToString());
  1049. Span<char> span = new char[str.Length + 2];
  1050. span[0] = '[';
  1051. str.CopyTo(span.Slice(1));
  1052. span[^1] = ']';
  1053. return GetLocalApiUrl(span);
  1054. }
  1055. return GetLocalApiUrl(ipAddress.ToString());
  1056. }
  1057. /// <inheritdoc/>
  1058. public string GetLoopbackHttpApiUrl()
  1059. {
  1060. return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
  1061. }
  1062. /// <inheritdoc/>
  1063. public string GetLocalApiUrl(ReadOnlySpan<char> host, string scheme = null, int? port = null)
  1064. {
  1065. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  1066. // not. For consistency, always trim the trailing slash.
  1067. return new UriBuilder
  1068. {
  1069. Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
  1070. Host = host.ToString(),
  1071. Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
  1072. Path = ServerConfigurationManager.Configuration.BaseUrl
  1073. }.ToString().TrimEnd('/');
  1074. }
  1075. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1076. {
  1077. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1078. }
  1079. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1080. {
  1081. var addresses = ServerConfigurationManager
  1082. .Configuration
  1083. .LocalNetworkAddresses
  1084. .Select(x => NormalizeConfiguredLocalAddress(x))
  1085. .Where(i => i != null)
  1086. .ToList();
  1087. if (addresses.Count == 0)
  1088. {
  1089. addresses.AddRange(_networkManager.GetLocalIpAddresses());
  1090. }
  1091. var resultList = new List<IPAddress>();
  1092. foreach (var address in addresses)
  1093. {
  1094. if (!allowLoopback)
  1095. {
  1096. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1097. {
  1098. continue;
  1099. }
  1100. }
  1101. if (await IsLocalIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false))
  1102. {
  1103. resultList.Add(address);
  1104. if (limit > 0 && resultList.Count >= limit)
  1105. {
  1106. return resultList;
  1107. }
  1108. }
  1109. }
  1110. return resultList;
  1111. }
  1112. public IPAddress NormalizeConfiguredLocalAddress(ReadOnlySpan<char> address)
  1113. {
  1114. var index = address.Trim('/').IndexOf('/');
  1115. if (index != -1)
  1116. {
  1117. address = address.Slice(index + 1);
  1118. }
  1119. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1120. {
  1121. return result;
  1122. }
  1123. return null;
  1124. }
  1125. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1126. private async Task<bool> IsLocalIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1127. {
  1128. if (address.Equals(IPAddress.Loopback)
  1129. || address.Equals(IPAddress.IPv6Loopback))
  1130. {
  1131. return true;
  1132. }
  1133. var apiUrl = GetLocalApiUrl(address) + "/system/ping";
  1134. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1135. {
  1136. return cachedResult;
  1137. }
  1138. try
  1139. {
  1140. using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl);
  1141. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  1142. .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
  1143. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  1144. var result = await System.Text.Json.JsonSerializer.DeserializeAsync<string>(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false);
  1145. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1146. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1147. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1148. return valid;
  1149. }
  1150. catch (OperationCanceledException)
  1151. {
  1152. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1153. throw;
  1154. }
  1155. catch (Exception ex)
  1156. {
  1157. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1158. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1159. return false;
  1160. }
  1161. }
  1162. public string FriendlyName =>
  1163. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1164. ? Environment.MachineName
  1165. : ServerConfigurationManager.Configuration.ServerName;
  1166. /// <summary>
  1167. /// Shuts down.
  1168. /// </summary>
  1169. public async Task Shutdown()
  1170. {
  1171. if (IsShuttingDown)
  1172. {
  1173. return;
  1174. }
  1175. IsShuttingDown = true;
  1176. try
  1177. {
  1178. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1179. }
  1180. catch (Exception ex)
  1181. {
  1182. Logger.LogError(ex, "Error sending server shutdown notification");
  1183. }
  1184. ShutdownInternal();
  1185. }
  1186. protected abstract void ShutdownInternal();
  1187. public event EventHandler HasUpdateAvailableChanged;
  1188. private bool _hasUpdateAvailable;
  1189. public bool HasUpdateAvailable
  1190. {
  1191. get => _hasUpdateAvailable;
  1192. set
  1193. {
  1194. var fireEvent = value && !_hasUpdateAvailable;
  1195. _hasUpdateAvailable = value;
  1196. if (fireEvent)
  1197. {
  1198. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1199. }
  1200. }
  1201. }
  1202. /// <summary>
  1203. /// Removes the plugin.
  1204. /// </summary>
  1205. /// <param name="plugin">The plugin.</param>
  1206. public void RemovePlugin(IPlugin plugin)
  1207. {
  1208. var list = _plugins.ToList();
  1209. list.Remove(plugin);
  1210. _plugins = list.ToArray();
  1211. }
  1212. public IEnumerable<Assembly> GetApiPluginAssemblies()
  1213. {
  1214. var assemblies = _allConcreteTypes
  1215. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  1216. .Select(i => i.Assembly)
  1217. .Distinct();
  1218. foreach (var assembly in assemblies)
  1219. {
  1220. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  1221. yield return assembly;
  1222. }
  1223. }
  1224. public virtual void LaunchUrl(string url)
  1225. {
  1226. if (!CanLaunchWebBrowser)
  1227. {
  1228. throw new NotSupportedException();
  1229. }
  1230. var process = new Process
  1231. {
  1232. StartInfo = new ProcessStartInfo
  1233. {
  1234. FileName = url,
  1235. UseShellExecute = true,
  1236. ErrorDialog = false
  1237. },
  1238. EnableRaisingEvents = true
  1239. };
  1240. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1241. try
  1242. {
  1243. process.Start();
  1244. }
  1245. catch (Exception ex)
  1246. {
  1247. Logger.LogError(ex, "Error launching url: {url}", url);
  1248. throw;
  1249. }
  1250. }
  1251. public virtual void EnableLoopback(string appName)
  1252. {
  1253. }
  1254. private bool _disposed = false;
  1255. /// <summary>
  1256. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1257. /// </summary>
  1258. public void Dispose()
  1259. {
  1260. Dispose(true);
  1261. GC.SuppressFinalize(this);
  1262. }
  1263. /// <summary>
  1264. /// Releases unmanaged and - optionally - managed resources.
  1265. /// </summary>
  1266. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1267. protected virtual void Dispose(bool dispose)
  1268. {
  1269. if (_disposed)
  1270. {
  1271. return;
  1272. }
  1273. if (dispose)
  1274. {
  1275. var type = GetType();
  1276. Logger.LogInformation("Disposing {Type}", type.Name);
  1277. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1278. _disposableParts.Clear();
  1279. foreach (var part in parts)
  1280. {
  1281. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1282. try
  1283. {
  1284. part.Dispose();
  1285. }
  1286. catch (Exception ex)
  1287. {
  1288. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1289. }
  1290. }
  1291. }
  1292. _disposed = true;
  1293. }
  1294. }
  1295. internal class CertificateInfo
  1296. {
  1297. public string Path { get; set; }
  1298. public string Password { get; set; }
  1299. }
  1300. }