ApplicationHost.cs 57 KB

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