ApplicationHost.cs 58 KB

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