ApplicationHost.cs 59 KB

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