ApplicationHost.cs 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544
  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: Remove support for injecting ILogger completely
  463. serviceCollection.AddSingleton((provider) =>
  464. {
  465. Logger.LogWarning("Injecting ILogger directly is deprecated and should be replaced with ILogger<T>");
  466. return Logger;
  467. });
  468. // TODO: properly set up scoping and switch to AddDbContextPool
  469. serviceCollection.AddDbContext<JellyfinDb>(
  470. options => options.UseSqlite($"Filename={Path.Combine(ApplicationPaths.DataPath, "jellyfin.db")}"),
  471. ServiceLifetime.Transient);
  472. serviceCollection.AddSingleton<JellyfinDbProvider>();
  473. serviceCollection.AddSingleton(_fileSystemManager);
  474. serviceCollection.AddSingleton<TvdbClientManager>();
  475. serviceCollection.AddSingleton<IHttpClient, HttpClientManager.HttpClientManager>();
  476. serviceCollection.AddSingleton(_networkManager);
  477. serviceCollection.AddSingleton<IIsoManager, IsoManager>();
  478. serviceCollection.AddSingleton<ITaskManager, TaskManager>();
  479. serviceCollection.AddSingleton(_xmlSerializer);
  480. serviceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  481. serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  482. serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  483. serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  484. serviceCollection.AddSingleton<IZipClient, ZipClient>();
  485. serviceCollection.AddSingleton<IHttpResultFactory, HttpResultFactory>();
  486. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  487. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  488. serviceCollection.AddSingleton(ServerConfigurationManager);
  489. serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  490. serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  491. serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  492. serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  493. serviceCollection.AddSingleton<IDisplayPreferencesRepository, SqliteDisplayPreferencesRepository>();
  494. serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  495. serviceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  496. serviceCollection.AddSingleton<IUserRepository, SqliteUserRepository>();
  497. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  498. serviceCollection.AddTransient(provider => new Lazy<IDtoService>(provider.GetRequiredService<IDtoService>));
  499. serviceCollection.AddSingleton<IUserManager, UserManager>();
  500. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  501. // TODO: Add StartupOptions.FFmpegPath to IConfiguration and remove this custom activation
  502. serviceCollection.AddTransient(provider => new Lazy<EncodingHelper>(provider.GetRequiredService<EncodingHelper>));
  503. serviceCollection.AddSingleton<IMediaEncoder>(provider =>
  504. ActivatorUtilities.CreateInstance<MediaBrowser.MediaEncoding.Encoder.MediaEncoder>(provider, _startupOptions.FFmpegPath ?? string.Empty));
  505. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  506. serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  507. serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  508. serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  509. serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  510. serviceCollection.AddSingleton<IMusicManager, MusicManager>();
  511. serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  512. serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  513. serviceCollection.AddSingleton<ServiceController>();
  514. serviceCollection.AddSingleton<IHttpListener, WebSocketSharpListener>();
  515. serviceCollection.AddSingleton<IHttpServer, HttpListenerHost>();
  516. serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  517. serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  518. serviceCollection.AddSingleton<IDeviceManager, DeviceManager>();
  519. serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  520. serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  521. serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
  522. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  523. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  524. serviceCollection.AddSingleton<IDtoService, DtoService>();
  525. serviceCollection.AddSingleton<IChannelManager, ChannelManager>();
  526. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  527. serviceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  528. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  529. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  530. serviceCollection.AddSingleton<LiveTvDtoService>();
  531. serviceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  532. serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  533. serviceCollection.AddSingleton<INotificationManager, NotificationManager>();
  534. serviceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  535. serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
  536. serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  537. serviceCollection.AddSingleton<IActivityManager, ActivityManager>();
  538. serviceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  539. serviceCollection.AddSingleton<ISessionContext, SessionContext>();
  540. serviceCollection.AddSingleton<IAuthService, AuthService>();
  541. serviceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  542. serviceCollection.AddSingleton<IResourceFileManager, ResourceFileManager>();
  543. serviceCollection.AddSingleton<EncodingHelper>();
  544. serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  545. }
  546. /// <summary>
  547. /// Create services registered with the service container that need to be initialized at application startup.
  548. /// </summary>
  549. /// <returns>A task representing the service initialization operation.</returns>
  550. public async Task InitializeServices()
  551. {
  552. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  553. await localizationManager.LoadAll().ConfigureAwait(false);
  554. _mediaEncoder = Resolve<IMediaEncoder>();
  555. _sessionManager = Resolve<ISessionManager>();
  556. _httpServer = Resolve<IHttpServer>();
  557. _httpClient = Resolve<IHttpClient>();
  558. ((SqliteDisplayPreferencesRepository)Resolve<IDisplayPreferencesRepository>()).Initialize();
  559. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  560. ((SqliteUserRepository)Resolve<IUserRepository>()).Initialize();
  561. SetStaticProperties();
  562. var userManager = (UserManager)Resolve<IUserManager>();
  563. userManager.Initialize();
  564. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  565. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, userManager);
  566. FindParts();
  567. }
  568. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  569. {
  570. // Distinct these to prevent users from reporting problems that aren't actually problems
  571. var commandLineArgs = Environment
  572. .GetCommandLineArgs()
  573. .Distinct();
  574. // Get all relevant environment variables
  575. var allEnvVars = Environment.GetEnvironmentVariables();
  576. var relevantEnvVars = new Dictionary<object, object>();
  577. foreach (var key in allEnvVars.Keys)
  578. {
  579. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  580. {
  581. relevantEnvVars.Add(key, allEnvVars[key]);
  582. }
  583. }
  584. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  585. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  586. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  587. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  588. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  589. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  590. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  591. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  592. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  593. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  594. }
  595. private X509Certificate2 GetCertificate(CertificateInfo info)
  596. {
  597. var certificateLocation = info?.Path;
  598. if (string.IsNullOrWhiteSpace(certificateLocation))
  599. {
  600. return null;
  601. }
  602. try
  603. {
  604. if (!File.Exists(certificateLocation))
  605. {
  606. return null;
  607. }
  608. // Don't use an empty string password
  609. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  610. var localCert = new X509Certificate2(certificateLocation, password);
  611. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  612. if (!localCert.HasPrivateKey)
  613. {
  614. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  615. return null;
  616. }
  617. return localCert;
  618. }
  619. catch (Exception ex)
  620. {
  621. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  622. return null;
  623. }
  624. }
  625. /// <summary>
  626. /// Dirty hacks.
  627. /// </summary>
  628. private void SetStaticProperties()
  629. {
  630. // For now there's no real way to inject these properly
  631. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  632. BaseItem.ConfigurationManager = ServerConfigurationManager;
  633. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  634. BaseItem.ProviderManager = Resolve<IProviderManager>();
  635. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  636. BaseItem.ItemRepository = Resolve<IItemRepository>();
  637. User.UserManager = Resolve<IUserManager>();
  638. BaseItem.FileSystem = _fileSystemManager;
  639. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  640. BaseItem.ChannelManager = Resolve<IChannelManager>();
  641. Video.LiveTvManager = Resolve<ILiveTvManager>();
  642. Folder.UserViewManager = Resolve<IUserViewManager>();
  643. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  644. UserView.CollectionManager = Resolve<ICollectionManager>();
  645. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  646. CollectionFolder.XmlSerializer = _xmlSerializer;
  647. CollectionFolder.JsonSerializer = Resolve<IJsonSerializer>();
  648. CollectionFolder.ApplicationHost = this;
  649. AuthenticatedAttribute.AuthService = Resolve<IAuthService>();
  650. }
  651. /// <summary>
  652. /// Finds plugin components and register them with the appropriate services.
  653. /// </summary>
  654. private void FindParts()
  655. {
  656. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  657. {
  658. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  659. ConfigurationManager.SaveConfiguration();
  660. }
  661. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  662. _plugins = GetExports<IPlugin>()
  663. .Select(LoadPlugin)
  664. .Where(i => i != null)
  665. .ToArray();
  666. _httpServer.Init(GetExportTypes<IService>(), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  667. Resolve<ILibraryManager>().AddParts(
  668. GetExports<IResolverIgnoreRule>(),
  669. GetExports<IItemResolver>(),
  670. GetExports<IIntroProvider>(),
  671. GetExports<IBaseItemComparer>(),
  672. GetExports<ILibraryPostScanTask>());
  673. Resolve<IProviderManager>().AddParts(
  674. GetExports<IImageProvider>(),
  675. GetExports<IMetadataService>(),
  676. GetExports<IMetadataProvider>(),
  677. GetExports<IMetadataSaver>(),
  678. GetExports<IExternalId>());
  679. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  680. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  681. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  682. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  683. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  684. Resolve<IUserManager>().AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  685. Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>());
  686. }
  687. private IPlugin LoadPlugin(IPlugin plugin)
  688. {
  689. try
  690. {
  691. if (plugin is IPluginAssembly assemblyPlugin)
  692. {
  693. var assembly = plugin.GetType().Assembly;
  694. var assemblyName = assembly.GetName();
  695. var assemblyFilePath = assembly.Location;
  696. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  697. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  698. try
  699. {
  700. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  701. if (idAttributes.Length > 0)
  702. {
  703. var attribute = (GuidAttribute)idAttributes[0];
  704. var assemblyId = new Guid(attribute.Value);
  705. assemblyPlugin.SetId(assemblyId);
  706. }
  707. }
  708. catch (Exception ex)
  709. {
  710. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  711. }
  712. }
  713. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  714. {
  715. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  716. }
  717. }
  718. catch (Exception ex)
  719. {
  720. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  721. return null;
  722. }
  723. return plugin;
  724. }
  725. /// <summary>
  726. /// Discovers the types.
  727. /// </summary>
  728. protected void DiscoverTypes()
  729. {
  730. Logger.LogInformation("Loading assemblies");
  731. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  732. }
  733. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  734. {
  735. foreach (var ass in assemblies)
  736. {
  737. Type[] exportedTypes;
  738. try
  739. {
  740. exportedTypes = ass.GetExportedTypes();
  741. }
  742. catch (FileNotFoundException ex)
  743. {
  744. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  745. continue;
  746. }
  747. foreach (Type type in exportedTypes)
  748. {
  749. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  750. {
  751. yield return type;
  752. }
  753. }
  754. }
  755. }
  756. private CertificateInfo CertificateInfo { get; set; }
  757. public X509Certificate2 Certificate { get; private set; }
  758. private IEnumerable<string> GetUrlPrefixes()
  759. {
  760. var hosts = new[] { "+" };
  761. return hosts.SelectMany(i =>
  762. {
  763. var prefixes = new List<string>
  764. {
  765. "http://" + i + ":" + HttpPort + "/"
  766. };
  767. if (CertificateInfo != null)
  768. {
  769. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  770. }
  771. return prefixes;
  772. });
  773. }
  774. /// <summary>
  775. /// Called when [configuration updated].
  776. /// </summary>
  777. /// <param name="sender">The sender.</param>
  778. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  779. protected void OnConfigurationUpdated(object sender, EventArgs e)
  780. {
  781. var requiresRestart = false;
  782. // Don't do anything if these haven't been set yet
  783. if (HttpPort != 0 && HttpsPort != 0)
  784. {
  785. // Need to restart if ports have changed
  786. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  787. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  788. {
  789. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  790. {
  791. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  792. ServerConfigurationManager.SaveConfiguration();
  793. requiresRestart = true;
  794. }
  795. }
  796. }
  797. if (!_httpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  798. {
  799. requiresRestart = true;
  800. }
  801. var currentCertPath = CertificateInfo?.Path;
  802. var newCertPath = ServerConfigurationManager.Configuration.CertificatePath;
  803. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  804. {
  805. requiresRestart = true;
  806. }
  807. if (requiresRestart)
  808. {
  809. Logger.LogInformation("App needs to be restarted due to configuration change.");
  810. NotifyPendingRestart();
  811. }
  812. }
  813. /// <summary>
  814. /// Notifies that the kernel that a change has been made that requires a restart
  815. /// </summary>
  816. public void NotifyPendingRestart()
  817. {
  818. Logger.LogInformation("App needs to be restarted.");
  819. var changed = !HasPendingRestart;
  820. HasPendingRestart = true;
  821. if (changed)
  822. {
  823. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  824. }
  825. }
  826. /// <summary>
  827. /// Restarts this instance.
  828. /// </summary>
  829. public void Restart()
  830. {
  831. if (!CanSelfRestart)
  832. {
  833. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  834. }
  835. if (IsShuttingDown)
  836. {
  837. return;
  838. }
  839. IsShuttingDown = true;
  840. Task.Run(async () =>
  841. {
  842. try
  843. {
  844. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  845. }
  846. catch (Exception ex)
  847. {
  848. Logger.LogError(ex, "Error sending server restart notification");
  849. }
  850. Logger.LogInformation("Calling RestartInternal");
  851. RestartInternal();
  852. });
  853. }
  854. protected abstract void RestartInternal();
  855. /// <summary>
  856. /// Gets the composable part assemblies.
  857. /// </summary>
  858. /// <returns>IEnumerable{Assembly}.</returns>
  859. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  860. {
  861. if (Directory.Exists(ApplicationPaths.PluginsPath))
  862. {
  863. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  864. {
  865. Assembly plugAss;
  866. try
  867. {
  868. plugAss = Assembly.LoadFrom(file);
  869. }
  870. catch (FileLoadException ex)
  871. {
  872. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  873. continue;
  874. }
  875. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  876. yield return plugAss;
  877. }
  878. }
  879. // Include composable parts in the Api assembly
  880. yield return typeof(ApiEntryPoint).Assembly;
  881. // Include composable parts in the Dashboard assembly
  882. yield return typeof(DashboardService).Assembly;
  883. // Include composable parts in the Model assembly
  884. yield return typeof(SystemInfo).Assembly;
  885. // Include composable parts in the Common assembly
  886. yield return typeof(IApplicationHost).Assembly;
  887. // Include composable parts in the Controller assembly
  888. yield return typeof(IServerApplicationHost).Assembly;
  889. // Include composable parts in the Providers assembly
  890. yield return typeof(ProviderUtils).Assembly;
  891. // Include composable parts in the Photos assembly
  892. yield return typeof(PhotoProvider).Assembly;
  893. // Emby.Server implementations
  894. yield return typeof(InstallationManager).Assembly;
  895. // MediaEncoding
  896. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  897. // Dlna
  898. yield return typeof(DlnaEntryPoint).Assembly;
  899. // Local metadata
  900. yield return typeof(BoxSetXmlSaver).Assembly;
  901. // Notifications
  902. yield return typeof(NotificationManager).Assembly;
  903. // Xbmc
  904. yield return typeof(ArtistNfoProvider).Assembly;
  905. foreach (var i in GetAssembliesWithPartsInternal())
  906. {
  907. yield return i;
  908. }
  909. }
  910. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  911. /// <summary>
  912. /// Gets the system status.
  913. /// </summary>
  914. /// <param name="cancellationToken">The cancellation token.</param>
  915. /// <returns>SystemInfo.</returns>
  916. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  917. {
  918. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  919. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  920. return new SystemInfo
  921. {
  922. HasPendingRestart = HasPendingRestart,
  923. IsShuttingDown = IsShuttingDown,
  924. Version = ApplicationVersionString,
  925. WebSocketPortNumber = HttpPort,
  926. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  927. Id = SystemId,
  928. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  929. WebPath = ApplicationPaths.WebPath,
  930. LogPath = ApplicationPaths.LogDirectoryPath,
  931. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  932. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  933. CachePath = ApplicationPaths.CachePath,
  934. HttpServerPortNumber = HttpPort,
  935. SupportsHttps = SupportsHttps,
  936. HttpsPortNumber = HttpsPort,
  937. OperatingSystem = OperatingSystem.Id.ToString(),
  938. OperatingSystemDisplayName = OperatingSystem.Name,
  939. CanSelfRestart = CanSelfRestart,
  940. CanLaunchWebBrowser = CanLaunchWebBrowser,
  941. HasUpdateAvailable = HasUpdateAvailable,
  942. TranscodingTempPath = transcodingTempPath,
  943. ServerName = FriendlyName,
  944. LocalAddress = localAddress,
  945. SupportsLibraryMonitor = true,
  946. EncoderLocation = _mediaEncoder.EncoderLocation,
  947. SystemArchitecture = RuntimeInformation.OSArchitecture,
  948. PackageName = _startupOptions.PackageName
  949. };
  950. }
  951. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  952. => _networkManager.GetMacAddresses()
  953. .Select(i => new WakeOnLanInfo(i))
  954. .ToList();
  955. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  956. {
  957. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  958. return new PublicSystemInfo
  959. {
  960. Version = ApplicationVersionString,
  961. ProductName = ApplicationProductName,
  962. Id = SystemId,
  963. OperatingSystem = OperatingSystem.Id.ToString(),
  964. ServerName = FriendlyName,
  965. LocalAddress = localAddress
  966. };
  967. }
  968. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  969. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  970. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken, bool forceHttp = false)
  971. {
  972. try
  973. {
  974. // Return the first matched address, if found, or the first known local address
  975. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  976. foreach (var address in addresses)
  977. {
  978. return GetLocalApiUrl(address, forceHttp);
  979. }
  980. return null;
  981. }
  982. catch (Exception ex)
  983. {
  984. Logger.LogError(ex, "Error getting local Ip address information");
  985. }
  986. return null;
  987. }
  988. /// <summary>
  989. /// Removes the scope id from IPv6 addresses.
  990. /// </summary>
  991. /// <param name="address">The IPv6 address.</param>
  992. /// <returns>The IPv6 address without the scope id.</returns>
  993. private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
  994. {
  995. var index = address.IndexOf('%');
  996. if (index == -1)
  997. {
  998. return address;
  999. }
  1000. return address.Slice(0, index);
  1001. }
  1002. /// <inheritdoc />
  1003. public string GetLocalApiUrl(IPAddress ipAddress, bool forceHttp = false)
  1004. {
  1005. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1006. {
  1007. var str = RemoveScopeId(ipAddress.ToString());
  1008. Span<char> span = new char[str.Length + 2];
  1009. span[0] = '[';
  1010. str.CopyTo(span.Slice(1));
  1011. span[^1] = ']';
  1012. return GetLocalApiUrl(span, forceHttp);
  1013. }
  1014. return GetLocalApiUrl(ipAddress.ToString(), forceHttp);
  1015. }
  1016. /// <inheritdoc />
  1017. public string GetLocalApiUrl(ReadOnlySpan<char> host, bool forceHttp = false)
  1018. {
  1019. var url = new StringBuilder(64);
  1020. bool useHttps = EnableHttps && !forceHttp;
  1021. url.Append(useHttps ? "https://" : "http://")
  1022. .Append(host)
  1023. .Append(':')
  1024. .Append(useHttps ? HttpsPort : HttpPort);
  1025. string baseUrl = ServerConfigurationManager.Configuration.BaseUrl;
  1026. if (baseUrl.Length != 0)
  1027. {
  1028. url.Append(baseUrl);
  1029. }
  1030. return url.ToString();
  1031. }
  1032. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1033. {
  1034. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1035. }
  1036. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1037. {
  1038. var addresses = ServerConfigurationManager
  1039. .Configuration
  1040. .LocalNetworkAddresses
  1041. .Select(NormalizeConfiguredLocalAddress)
  1042. .Where(i => i != null)
  1043. .ToList();
  1044. if (addresses.Count == 0)
  1045. {
  1046. addresses.AddRange(_networkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1047. }
  1048. var resultList = new List<IPAddress>();
  1049. foreach (var address in addresses)
  1050. {
  1051. if (!allowLoopback)
  1052. {
  1053. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1054. {
  1055. continue;
  1056. }
  1057. }
  1058. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1059. if (valid)
  1060. {
  1061. resultList.Add(address);
  1062. if (limit > 0 && resultList.Count >= limit)
  1063. {
  1064. return resultList;
  1065. }
  1066. }
  1067. }
  1068. return resultList;
  1069. }
  1070. public IPAddress NormalizeConfiguredLocalAddress(string address)
  1071. {
  1072. var index = address.Trim('/').IndexOf('/');
  1073. if (index != -1)
  1074. {
  1075. address = address.Substring(index + 1);
  1076. }
  1077. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1078. {
  1079. return result;
  1080. }
  1081. return null;
  1082. }
  1083. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1084. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1085. {
  1086. if (address.Equals(IPAddress.Loopback)
  1087. || address.Equals(IPAddress.IPv6Loopback))
  1088. {
  1089. return true;
  1090. }
  1091. var apiUrl = GetLocalApiUrl(address);
  1092. apiUrl += "/system/ping";
  1093. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1094. {
  1095. return cachedResult;
  1096. }
  1097. try
  1098. {
  1099. using (var response = await _httpClient.SendAsync(
  1100. new HttpRequestOptions
  1101. {
  1102. Url = apiUrl,
  1103. LogErrorResponseBody = false,
  1104. BufferContent = false,
  1105. CancellationToken = cancellationToken
  1106. }, HttpMethod.Post).ConfigureAwait(false))
  1107. {
  1108. using (var reader = new StreamReader(response.Content))
  1109. {
  1110. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1111. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1112. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1113. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1114. return valid;
  1115. }
  1116. }
  1117. }
  1118. catch (OperationCanceledException)
  1119. {
  1120. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1121. throw;
  1122. }
  1123. catch (Exception ex)
  1124. {
  1125. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1126. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1127. return false;
  1128. }
  1129. }
  1130. public string FriendlyName =>
  1131. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1132. ? Environment.MachineName
  1133. : ServerConfigurationManager.Configuration.ServerName;
  1134. /// <summary>
  1135. /// Shuts down.
  1136. /// </summary>
  1137. public async Task Shutdown()
  1138. {
  1139. if (IsShuttingDown)
  1140. {
  1141. return;
  1142. }
  1143. IsShuttingDown = true;
  1144. try
  1145. {
  1146. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1147. }
  1148. catch (Exception ex)
  1149. {
  1150. Logger.LogError(ex, "Error sending server shutdown notification");
  1151. }
  1152. ShutdownInternal();
  1153. }
  1154. protected abstract void ShutdownInternal();
  1155. public event EventHandler HasUpdateAvailableChanged;
  1156. private bool _hasUpdateAvailable;
  1157. public bool HasUpdateAvailable
  1158. {
  1159. get => _hasUpdateAvailable;
  1160. set
  1161. {
  1162. var fireEvent = value && !_hasUpdateAvailable;
  1163. _hasUpdateAvailable = value;
  1164. if (fireEvent)
  1165. {
  1166. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1167. }
  1168. }
  1169. }
  1170. /// <summary>
  1171. /// Removes the plugin.
  1172. /// </summary>
  1173. /// <param name="plugin">The plugin.</param>
  1174. public void RemovePlugin(IPlugin plugin)
  1175. {
  1176. var list = _plugins.ToList();
  1177. list.Remove(plugin);
  1178. _plugins = list.ToArray();
  1179. }
  1180. public virtual void LaunchUrl(string url)
  1181. {
  1182. if (!CanLaunchWebBrowser)
  1183. {
  1184. throw new NotSupportedException();
  1185. }
  1186. var process = new Process
  1187. {
  1188. StartInfo = new ProcessStartInfo
  1189. {
  1190. FileName = url,
  1191. UseShellExecute = true,
  1192. ErrorDialog = false
  1193. },
  1194. EnableRaisingEvents = true
  1195. };
  1196. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1197. try
  1198. {
  1199. process.Start();
  1200. }
  1201. catch (Exception ex)
  1202. {
  1203. Logger.LogError(ex, "Error launching url: {url}", url);
  1204. throw;
  1205. }
  1206. }
  1207. public virtual void EnableLoopback(string appName)
  1208. {
  1209. }
  1210. private bool _disposed = false;
  1211. /// <summary>
  1212. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1213. /// </summary>
  1214. public void Dispose()
  1215. {
  1216. Dispose(true);
  1217. GC.SuppressFinalize(this);
  1218. }
  1219. /// <summary>
  1220. /// Releases unmanaged and - optionally - managed resources.
  1221. /// </summary>
  1222. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1223. protected virtual void Dispose(bool dispose)
  1224. {
  1225. if (_disposed)
  1226. {
  1227. return;
  1228. }
  1229. if (dispose)
  1230. {
  1231. var type = GetType();
  1232. Logger.LogInformation("Disposing {Type}", type.Name);
  1233. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1234. _disposableParts.Clear();
  1235. foreach (var part in parts)
  1236. {
  1237. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1238. try
  1239. {
  1240. part.Dispose();
  1241. }
  1242. catch (Exception ex)
  1243. {
  1244. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1245. }
  1246. }
  1247. }
  1248. _disposed = true;
  1249. }
  1250. }
  1251. internal class CertificateInfo
  1252. {
  1253. public string Path { get; set; }
  1254. public string Password { get; set; }
  1255. }
  1256. }