ApplicationHost.cs 57 KB

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