ApplicationHost.cs 55 KB

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