ApplicationHost.cs 55 KB

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