ApplicationHost.cs 56 KB

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