ApplicationHost.cs 56 KB

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