ApplicationHost.cs 59 KB

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