ApplicationHost.cs 56 KB

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