ApplicationHost.cs 56 KB

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