ApplicationHost.cs 58 KB

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