ApplicationHost.cs 58 KB

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