ApplicationHost.cs 55 KB

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