ApplicationHost.cs 58 KB

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