ApplicationHost.cs 59 KB

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