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