ApplicationHost.cs 59 KB

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