ApplicationHost.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Reflection;
  12. using System.Security.Cryptography.X509Certificates;
  13. using System.Threading.Tasks;
  14. using Emby.Dlna.Main;
  15. using Emby.Naming.Common;
  16. using Emby.Photos;
  17. using Emby.Server.Implementations.Channels;
  18. using Emby.Server.Implementations.Collections;
  19. using Emby.Server.Implementations.Configuration;
  20. using Emby.Server.Implementations.Cryptography;
  21. using Emby.Server.Implementations.Data;
  22. using Emby.Server.Implementations.Devices;
  23. using Emby.Server.Implementations.Dto;
  24. using Emby.Server.Implementations.HttpServer.Security;
  25. using Emby.Server.Implementations.IO;
  26. using Emby.Server.Implementations.Library;
  27. using Emby.Server.Implementations.LiveTv;
  28. using Emby.Server.Implementations.Localization;
  29. using Emby.Server.Implementations.Net;
  30. using Emby.Server.Implementations.Playlists;
  31. using Emby.Server.Implementations.Plugins;
  32. using Emby.Server.Implementations.QuickConnect;
  33. using Emby.Server.Implementations.ScheduledTasks;
  34. using Emby.Server.Implementations.Serialization;
  35. using Emby.Server.Implementations.Session;
  36. using Emby.Server.Implementations.SyncPlay;
  37. using Emby.Server.Implementations.TV;
  38. using Emby.Server.Implementations.Updates;
  39. using Jellyfin.Api.Helpers;
  40. using Jellyfin.Drawing;
  41. using Jellyfin.MediaEncoding.Hls.Playlist;
  42. using Jellyfin.Networking.Manager;
  43. using Jellyfin.Server.Implementations;
  44. using MediaBrowser.Common;
  45. using MediaBrowser.Common.Configuration;
  46. using MediaBrowser.Common.Events;
  47. using MediaBrowser.Common.Net;
  48. using MediaBrowser.Common.Plugins;
  49. using MediaBrowser.Common.Updates;
  50. using MediaBrowser.Controller;
  51. using MediaBrowser.Controller.Channels;
  52. using MediaBrowser.Controller.Chapters;
  53. using MediaBrowser.Controller.ClientEvent;
  54. using MediaBrowser.Controller.Collections;
  55. using MediaBrowser.Controller.Configuration;
  56. using MediaBrowser.Controller.Drawing;
  57. using MediaBrowser.Controller.Dto;
  58. using MediaBrowser.Controller.Entities;
  59. using MediaBrowser.Controller.Library;
  60. using MediaBrowser.Controller.LiveTv;
  61. using MediaBrowser.Controller.Lyrics;
  62. using MediaBrowser.Controller.MediaEncoding;
  63. using MediaBrowser.Controller.Net;
  64. using MediaBrowser.Controller.Persistence;
  65. using MediaBrowser.Controller.Playlists;
  66. using MediaBrowser.Controller.Plugins;
  67. using MediaBrowser.Controller.Providers;
  68. using MediaBrowser.Controller.QuickConnect;
  69. using MediaBrowser.Controller.Resolvers;
  70. using MediaBrowser.Controller.Session;
  71. using MediaBrowser.Controller.Sorting;
  72. using MediaBrowser.Controller.Subtitles;
  73. using MediaBrowser.Controller.SyncPlay;
  74. using MediaBrowser.Controller.TV;
  75. using MediaBrowser.LocalMetadata.Savers;
  76. using MediaBrowser.MediaEncoding.BdInfo;
  77. using MediaBrowser.MediaEncoding.Subtitles;
  78. using MediaBrowser.Model.Cryptography;
  79. using MediaBrowser.Model.Globalization;
  80. using MediaBrowser.Model.IO;
  81. using MediaBrowser.Model.MediaInfo;
  82. using MediaBrowser.Model.Net;
  83. using MediaBrowser.Model.Serialization;
  84. using MediaBrowser.Model.System;
  85. using MediaBrowser.Model.Tasks;
  86. using MediaBrowser.Providers.Chapters;
  87. using MediaBrowser.Providers.Lyric;
  88. using MediaBrowser.Providers.Manager;
  89. using MediaBrowser.Providers.Plugins.Tmdb;
  90. using MediaBrowser.Providers.Subtitles;
  91. using MediaBrowser.XbmcMetadata.Providers;
  92. using Microsoft.AspNetCore.Http;
  93. using Microsoft.AspNetCore.Mvc;
  94. using Microsoft.EntityFrameworkCore;
  95. using Microsoft.Extensions.Configuration;
  96. using Microsoft.Extensions.DependencyInjection;
  97. using Microsoft.Extensions.Logging;
  98. using Prometheus.DotNetRuntime;
  99. using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
  100. using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
  101. namespace Emby.Server.Implementations
  102. {
  103. /// <summary>
  104. /// Class CompositionRoot.
  105. /// </summary>
  106. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  107. {
  108. /// <summary>
  109. /// The disposable parts.
  110. /// </summary>
  111. private readonly ConcurrentDictionary<IDisposable, byte> _disposableParts = new();
  112. private readonly DeviceId _deviceId;
  113. private readonly IConfiguration _startupConfig;
  114. private readonly IXmlSerializer _xmlSerializer;
  115. private readonly IStartupOptions _startupOptions;
  116. private readonly IPluginManager _pluginManager;
  117. private List<Type> _creatingInstances;
  118. /// <summary>
  119. /// Gets or sets all concrete types.
  120. /// </summary>
  121. /// <value>All concrete types.</value>
  122. private Type[] _allConcreteTypes;
  123. private bool _disposed;
  124. /// <summary>
  125. /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
  126. /// </summary>
  127. /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
  128. /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
  129. /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
  130. /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param>
  131. protected ApplicationHost(
  132. IServerApplicationPaths applicationPaths,
  133. ILoggerFactory loggerFactory,
  134. IStartupOptions options,
  135. IConfiguration startupConfig)
  136. {
  137. ApplicationPaths = applicationPaths;
  138. LoggerFactory = loggerFactory;
  139. _startupOptions = options;
  140. _startupConfig = startupConfig;
  141. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  142. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  143. ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
  144. ApplicationVersionString = ApplicationVersion.ToString(3);
  145. ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  146. _xmlSerializer = new MyXmlSerializer();
  147. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer);
  148. _pluginManager = new PluginManager(
  149. LoggerFactory.CreateLogger<PluginManager>(),
  150. this,
  151. ConfigurationManager.Configuration,
  152. ApplicationPaths.PluginsPath,
  153. ApplicationVersion);
  154. _disposableParts.TryAdd((PluginManager)_pluginManager, byte.MinValue);
  155. }
  156. /// <summary>
  157. /// Occurs when [has pending restart changed].
  158. /// </summary>
  159. public event EventHandler HasPendingRestartChanged;
  160. /// <summary>
  161. /// Gets the value of the PublishedServerUrl setting.
  162. /// </summary>
  163. private string PublishedServerUrl => _startupConfig[AddressOverrideKey];
  164. public bool CoreStartupHasCompleted { get; private set; }
  165. /// <summary>
  166. /// Gets the <see cref="INetworkManager"/> singleton instance.
  167. /// </summary>
  168. public INetworkManager NetManager { get; private set; }
  169. /// <inheritdoc />
  170. public bool HasPendingRestart { get; private set; }
  171. /// <inheritdoc />
  172. public bool ShouldRestart { get; set; }
  173. /// <summary>
  174. /// Gets the logger.
  175. /// </summary>
  176. protected ILogger<ApplicationHost> Logger { get; }
  177. /// <summary>
  178. /// Gets the logger factory.
  179. /// </summary>
  180. protected ILoggerFactory LoggerFactory { get; }
  181. /// <summary>
  182. /// Gets the application paths.
  183. /// </summary>
  184. /// <value>The application paths.</value>
  185. protected IServerApplicationPaths ApplicationPaths { get; }
  186. /// <summary>
  187. /// Gets the configuration manager.
  188. /// </summary>
  189. /// <value>The configuration manager.</value>
  190. public ServerConfigurationManager ConfigurationManager { get; }
  191. /// <summary>
  192. /// Gets or sets the service provider.
  193. /// </summary>
  194. public IServiceProvider ServiceProvider { get; set; }
  195. /// <summary>
  196. /// Gets the http port for the webhost.
  197. /// </summary>
  198. public int HttpPort { get; private set; }
  199. /// <summary>
  200. /// Gets the https port for the webhost.
  201. /// </summary>
  202. public int HttpsPort { get; private set; }
  203. /// <inheritdoc />
  204. public Version ApplicationVersion { get; }
  205. /// <inheritdoc />
  206. public string ApplicationVersionString { get; }
  207. /// <summary>
  208. /// Gets the current application user agent.
  209. /// </summary>
  210. /// <value>The application user agent.</value>
  211. public string ApplicationUserAgent { get; }
  212. /// <summary>
  213. /// Gets the email address for use within a comment section of a user agent field.
  214. /// Presently used to provide contact information to MusicBrainz service.
  215. /// </summary>
  216. public string ApplicationUserAgentAddress => "team@jellyfin.org";
  217. /// <summary>
  218. /// Gets the current application name.
  219. /// </summary>
  220. /// <value>The application name.</value>
  221. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  222. public string SystemId => _deviceId.Value;
  223. /// <inheritdoc/>
  224. public string Name => ApplicationProductName;
  225. private string CertificatePath { get; set; }
  226. public X509Certificate2 Certificate { get; private set; }
  227. /// <inheritdoc/>
  228. public bool ListenWithHttps => Certificate is not null && ConfigurationManager.GetNetworkConfiguration().EnableHttps;
  229. public string FriendlyName =>
  230. string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName)
  231. ? Environment.MachineName
  232. : ConfigurationManager.Configuration.ServerName;
  233. public string ExpandVirtualPath(string path)
  234. {
  235. var appPaths = ApplicationPaths;
  236. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  237. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  238. }
  239. public string ReverseVirtualPath(string path)
  240. {
  241. var appPaths = ApplicationPaths;
  242. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  243. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  244. }
  245. /// <summary>
  246. /// Creates the instance safe.
  247. /// </summary>
  248. /// <param name="type">The type.</param>
  249. /// <returns>System.Object.</returns>
  250. protected object CreateInstanceSafe(Type type)
  251. {
  252. _creatingInstances ??= new List<Type>();
  253. if (_creatingInstances.Contains(type))
  254. {
  255. Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
  256. foreach (var entry in _creatingInstances)
  257. {
  258. Logger.LogError("Called from: {TypeName}", entry.FullName);
  259. }
  260. _pluginManager.FailPlugin(type.Assembly);
  261. throw new TypeLoadException("DI Loop detected");
  262. }
  263. try
  264. {
  265. _creatingInstances.Add(type);
  266. Logger.LogDebug("Creating instance of {Type}", type);
  267. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  268. }
  269. catch (Exception ex)
  270. {
  271. Logger.LogError(ex, "Error creating {Type}", type);
  272. // If this is a plugin fail it.
  273. _pluginManager.FailPlugin(type.Assembly);
  274. return null;
  275. }
  276. finally
  277. {
  278. _creatingInstances.Remove(type);
  279. }
  280. }
  281. /// <summary>
  282. /// Resolves this instance.
  283. /// </summary>
  284. /// <typeparam name="T">The type.</typeparam>
  285. /// <returns>``0.</returns>
  286. public T Resolve<T>() => ServiceProvider.GetService<T>();
  287. /// <inheritdoc/>
  288. public IEnumerable<Type> GetExportTypes<T>()
  289. {
  290. var currentType = typeof(T);
  291. var numberOfConcreteTypes = _allConcreteTypes.Length;
  292. for (var i = 0; i < numberOfConcreteTypes; i++)
  293. {
  294. var type = _allConcreteTypes[i];
  295. if (currentType.IsAssignableFrom(type))
  296. {
  297. yield return type;
  298. }
  299. }
  300. }
  301. /// <inheritdoc />
  302. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  303. {
  304. // Convert to list so this isn't executed for each iteration
  305. var parts = GetExportTypes<T>()
  306. .Select(CreateInstanceSafe)
  307. .Where(i => i is not null)
  308. .Cast<T>()
  309. .ToList();
  310. if (manageLifetime)
  311. {
  312. foreach (var part in parts.OfType<IDisposable>())
  313. {
  314. _disposableParts.TryAdd(part, byte.MinValue);
  315. }
  316. }
  317. return parts;
  318. }
  319. /// <inheritdoc />
  320. public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
  321. {
  322. // Convert to list so this isn't executed for each iteration
  323. var parts = GetExportTypes<T>()
  324. .Select(i => defaultFunc(i))
  325. .Where(i => i is not null)
  326. .Cast<T>()
  327. .ToList();
  328. if (manageLifetime)
  329. {
  330. foreach (var part in parts.OfType<IDisposable>())
  331. {
  332. _disposableParts.TryAdd(part, byte.MinValue);
  333. }
  334. }
  335. return parts;
  336. }
  337. /// <summary>
  338. /// Runs the startup tasks.
  339. /// </summary>
  340. /// <returns><see cref="Task" />.</returns>
  341. public async Task RunStartupTasksAsync()
  342. {
  343. Logger.LogInformation("Running startup tasks");
  344. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  345. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  346. ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
  347. Resolve<IMediaEncoder>().SetFFmpegPath();
  348. Logger.LogInformation("ServerId: {ServerId}", SystemId);
  349. var entryPoints = GetExports<IServerEntryPoint>();
  350. var stopWatch = new Stopwatch();
  351. stopWatch.Start();
  352. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  353. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  354. Logger.LogInformation("Core startup complete");
  355. CoreStartupHasCompleted = true;
  356. stopWatch.Restart();
  357. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  358. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  359. stopWatch.Stop();
  360. }
  361. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  362. {
  363. foreach (var entryPoint in entryPoints)
  364. {
  365. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  366. {
  367. continue;
  368. }
  369. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  370. yield return entryPoint.RunAsync();
  371. }
  372. }
  373. /// <inheritdoc/>
  374. public void Init(IServiceCollection serviceCollection)
  375. {
  376. DiscoverTypes();
  377. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  378. NetManager = new NetworkManager(ConfigurationManager, _startupConfig, LoggerFactory.CreateLogger<NetworkManager>());
  379. // Initialize runtime stat collection
  380. if (ConfigurationManager.Configuration.EnableMetrics)
  381. {
  382. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  383. }
  384. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  385. HttpPort = networkConfiguration.InternalHttpPort;
  386. HttpsPort = networkConfiguration.InternalHttpsPort;
  387. // Safeguard against invalid configuration
  388. if (HttpPort == HttpsPort)
  389. {
  390. HttpPort = NetworkConfiguration.DefaultHttpPort;
  391. HttpsPort = NetworkConfiguration.DefaultHttpsPort;
  392. }
  393. CertificatePath = networkConfiguration.CertificatePath;
  394. Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword);
  395. RegisterServices(serviceCollection);
  396. _pluginManager.RegisterServices(serviceCollection);
  397. }
  398. /// <summary>
  399. /// Registers services/resources with the service collection that will be available via DI.
  400. /// </summary>
  401. /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
  402. protected virtual void RegisterServices(IServiceCollection serviceCollection)
  403. {
  404. serviceCollection.AddSingleton(_startupOptions);
  405. serviceCollection.AddMemoryCache();
  406. serviceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
  407. serviceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
  408. serviceCollection.AddSingleton<IApplicationHost>(this);
  409. serviceCollection.AddSingleton(_pluginManager);
  410. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  411. serviceCollection.AddSingleton<IFileSystem, ManagedFileSystem>();
  412. serviceCollection.AddSingleton<IShortcutHandler, MbLinkShortcutHandler>();
  413. serviceCollection.AddScoped<ISystemManager, SystemManager>();
  414. serviceCollection.AddSingleton<TmdbClientManager>();
  415. serviceCollection.AddSingleton(NetManager);
  416. serviceCollection.AddSingleton<ITaskManager, TaskManager>();
  417. serviceCollection.AddSingleton(_xmlSerializer);
  418. serviceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  419. serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  420. serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  421. serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  422. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  423. serviceCollection.AddSingleton(ApplicationPaths);
  424. serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  425. serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  426. serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  427. serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  428. serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  429. serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  430. serviceCollection.AddSingleton<EncodingHelper>();
  431. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  432. serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  433. serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  434. serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  435. serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  436. serviceCollection.AddSingleton<NamingOptions>();
  437. serviceCollection.AddSingleton<IMusicManager, MusicManager>();
  438. serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  439. serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  440. serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  441. serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  442. serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  443. serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  444. serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  445. serviceCollection.AddSingleton<ILyricManager, LyricManager>();
  446. serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
  447. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  448. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  449. serviceCollection.AddSingleton<IDtoService, DtoService>();
  450. serviceCollection.AddSingleton<IChannelManager, ChannelManager>();
  451. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  452. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  453. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  454. serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  455. serviceCollection.AddSingleton<LiveTvDtoService>();
  456. serviceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  457. serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  458. serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
  459. serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  460. serviceCollection.AddSingleton<IAuthService, AuthService>();
  461. serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  462. serviceCollection.AddSingleton<ISubtitleParser, SubtitleEditParser>();
  463. serviceCollection.AddSingleton<ISubtitleEncoder, SubtitleEncoder>();
  464. serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  465. serviceCollection.AddSingleton<TranscodingJobHelper>();
  466. serviceCollection.AddScoped<MediaInfoHelper>();
  467. serviceCollection.AddScoped<AudioHelper>();
  468. serviceCollection.AddScoped<DynamicHlsHelper>();
  469. serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>();
  470. serviceCollection.AddSingleton<IDirectoryService, DirectoryService>();
  471. }
  472. /// <summary>
  473. /// Create services registered with the service container that need to be initialized at application startup.
  474. /// </summary>
  475. /// <returns>A task representing the service initialization operation.</returns>
  476. public async Task InitializeServices()
  477. {
  478. var jellyfinDb = await Resolve<IDbContextFactory<JellyfinDbContext>>().CreateDbContextAsync().ConfigureAwait(false);
  479. await using (jellyfinDb.ConfigureAwait(false))
  480. {
  481. if ((await jellyfinDb.Database.GetPendingMigrationsAsync().ConfigureAwait(false)).Any())
  482. {
  483. Logger.LogInformation("There are pending EFCore migrations in the database. Applying... (This may take a while, do not stop Jellyfin)");
  484. await jellyfinDb.Database.MigrateAsync().ConfigureAwait(false);
  485. Logger.LogInformation("EFCore migrations applied successfully");
  486. }
  487. }
  488. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize();
  489. ((SqliteUserDataRepository)Resolve<IUserDataRepository>()).Initialize();
  490. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  491. await localizationManager.LoadAll().ConfigureAwait(false);
  492. SetStaticProperties();
  493. FindParts();
  494. }
  495. private X509Certificate2 GetCertificate(string path, string password)
  496. {
  497. if (string.IsNullOrWhiteSpace(path))
  498. {
  499. return null;
  500. }
  501. try
  502. {
  503. if (!File.Exists(path))
  504. {
  505. return null;
  506. }
  507. // Don't use an empty string password
  508. password = string.IsNullOrWhiteSpace(password) ? null : password;
  509. var localCert = new X509Certificate2(path, password, X509KeyStorageFlags.UserKeySet);
  510. if (!localCert.HasPrivateKey)
  511. {
  512. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
  513. return null;
  514. }
  515. return localCert;
  516. }
  517. catch (Exception ex)
  518. {
  519. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
  520. return null;
  521. }
  522. }
  523. /// <summary>
  524. /// Dirty hacks.
  525. /// </summary>
  526. private void SetStaticProperties()
  527. {
  528. // For now there's no real way to inject these properly
  529. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  530. BaseItem.ConfigurationManager = ConfigurationManager;
  531. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  532. BaseItem.ProviderManager = Resolve<IProviderManager>();
  533. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  534. BaseItem.ItemRepository = Resolve<IItemRepository>();
  535. BaseItem.FileSystem = Resolve<IFileSystem>();
  536. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  537. BaseItem.ChannelManager = Resolve<IChannelManager>();
  538. Video.LiveTvManager = Resolve<ILiveTvManager>();
  539. Folder.UserViewManager = Resolve<IUserViewManager>();
  540. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  541. UserView.CollectionManager = Resolve<ICollectionManager>();
  542. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  543. CollectionFolder.XmlSerializer = _xmlSerializer;
  544. CollectionFolder.ApplicationHost = this;
  545. }
  546. /// <summary>
  547. /// Finds plugin components and register them with the appropriate services.
  548. /// </summary>
  549. private void FindParts()
  550. {
  551. if (!ConfigurationManager.Configuration.IsPortAuthorized)
  552. {
  553. ConfigurationManager.Configuration.IsPortAuthorized = true;
  554. ConfigurationManager.SaveConfiguration();
  555. }
  556. _pluginManager.CreatePlugins();
  557. Resolve<ILibraryManager>().AddParts(
  558. GetExports<IResolverIgnoreRule>(),
  559. GetExports<IItemResolver>(),
  560. GetExports<IIntroProvider>(),
  561. GetExports<IBaseItemComparer>(),
  562. GetExports<ILibraryPostScanTask>());
  563. Resolve<IProviderManager>().AddParts(
  564. GetExports<IImageProvider>(),
  565. GetExports<IMetadataService>(),
  566. GetExports<IMetadataProvider>(),
  567. GetExports<IMetadataSaver>(),
  568. GetExports<IExternalId>());
  569. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  570. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  571. }
  572. /// <summary>
  573. /// Discovers the types.
  574. /// </summary>
  575. protected void DiscoverTypes()
  576. {
  577. Logger.LogInformation("Loading assemblies");
  578. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  579. }
  580. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  581. {
  582. foreach (var ass in assemblies)
  583. {
  584. Type[] exportedTypes;
  585. try
  586. {
  587. exportedTypes = ass.GetExportedTypes();
  588. }
  589. catch (FileNotFoundException ex)
  590. {
  591. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  592. _pluginManager.FailPlugin(ass);
  593. continue;
  594. }
  595. catch (TypeLoadException ex)
  596. {
  597. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  598. _pluginManager.FailPlugin(ass);
  599. continue;
  600. }
  601. foreach (Type type in exportedTypes)
  602. {
  603. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  604. {
  605. yield return type;
  606. }
  607. }
  608. }
  609. }
  610. /// <summary>
  611. /// Called when [configuration updated].
  612. /// </summary>
  613. /// <param name="sender">The sender.</param>
  614. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  615. private void OnConfigurationUpdated(object sender, EventArgs e)
  616. {
  617. var requiresRestart = false;
  618. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  619. // Don't do anything if these haven't been set yet
  620. if (HttpPort != 0 && HttpsPort != 0)
  621. {
  622. // Need to restart if ports have changed
  623. if (networkConfiguration.InternalHttpPort != HttpPort
  624. || networkConfiguration.InternalHttpsPort != HttpsPort)
  625. {
  626. if (ConfigurationManager.Configuration.IsPortAuthorized)
  627. {
  628. ConfigurationManager.Configuration.IsPortAuthorized = false;
  629. ConfigurationManager.SaveConfiguration();
  630. requiresRestart = true;
  631. }
  632. }
  633. }
  634. if (ValidateSslCertificate(networkConfiguration))
  635. {
  636. requiresRestart = true;
  637. }
  638. if (requiresRestart)
  639. {
  640. Logger.LogInformation("App needs to be restarted due to configuration change.");
  641. NotifyPendingRestart();
  642. }
  643. }
  644. /// <summary>
  645. /// Validates the SSL certificate.
  646. /// </summary>
  647. /// <param name="networkConfig">The new configuration.</param>
  648. /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
  649. private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
  650. {
  651. var newPath = networkConfig.CertificatePath;
  652. if (!string.IsNullOrWhiteSpace(newPath)
  653. && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
  654. {
  655. if (File.Exists(newPath))
  656. {
  657. return true;
  658. }
  659. throw new FileNotFoundException(
  660. string.Format(
  661. CultureInfo.InvariantCulture,
  662. "Certificate file '{0}' does not exist.",
  663. newPath));
  664. }
  665. return false;
  666. }
  667. /// <summary>
  668. /// Notifies the kernel that a change has been made that requires a restart.
  669. /// </summary>
  670. public void NotifyPendingRestart()
  671. {
  672. Logger.LogInformation("App needs to be restarted.");
  673. var changed = !HasPendingRestart;
  674. HasPendingRestart = true;
  675. if (changed)
  676. {
  677. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  678. }
  679. }
  680. /// <summary>
  681. /// Gets the composable part assemblies.
  682. /// </summary>
  683. /// <returns>IEnumerable{Assembly}.</returns>
  684. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  685. {
  686. foreach (var p in _pluginManager.LoadAssemblies())
  687. {
  688. yield return p;
  689. }
  690. // Include composable parts in the Model assembly
  691. yield return typeof(SystemInfo).Assembly;
  692. // Include composable parts in the Common assembly
  693. yield return typeof(IApplicationHost).Assembly;
  694. // Include composable parts in the Controller assembly
  695. yield return typeof(IServerApplicationHost).Assembly;
  696. // Include composable parts in the Providers assembly
  697. yield return typeof(ProviderManager).Assembly;
  698. // Include composable parts in the Photos assembly
  699. yield return typeof(PhotoProvider).Assembly;
  700. // Emby.Server implementations
  701. yield return typeof(InstallationManager).Assembly;
  702. // MediaEncoding
  703. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  704. // Dlna
  705. yield return typeof(DlnaHost).Assembly;
  706. // Local metadata
  707. yield return typeof(BoxSetXmlSaver).Assembly;
  708. // Xbmc
  709. yield return typeof(ArtistNfoProvider).Assembly;
  710. // Network
  711. yield return typeof(NetworkManager).Assembly;
  712. // Hls
  713. yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
  714. foreach (var i in GetAssembliesWithPartsInternal())
  715. {
  716. yield return i;
  717. }
  718. }
  719. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  720. /// <inheritdoc/>
  721. public string GetSmartApiUrl(IPAddress remoteAddr)
  722. {
  723. // Published server ends with a /
  724. if (!string.IsNullOrEmpty(PublishedServerUrl))
  725. {
  726. // Published server ends with a '/', so we need to remove it.
  727. return PublishedServerUrl.Trim('/');
  728. }
  729. string smart = NetManager.GetBindAddress(remoteAddr, out var port);
  730. return GetLocalApiUrl(smart.Trim('/'), null, port);
  731. }
  732. /// <inheritdoc/>
  733. public string GetSmartApiUrl(HttpRequest request)
  734. {
  735. // Return the host in the HTTP request as the API URL if not configured otherwise
  736. if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
  737. {
  738. int? requestPort = request.Host.Port;
  739. if (requestPort is null
  740. || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
  741. || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
  742. {
  743. requestPort = -1;
  744. }
  745. return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
  746. }
  747. return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
  748. }
  749. /// <inheritdoc/>
  750. public string GetSmartApiUrl(string hostname)
  751. {
  752. // Published server ends with a /
  753. if (!string.IsNullOrEmpty(PublishedServerUrl))
  754. {
  755. // Published server ends with a '/', so we need to remove it.
  756. return PublishedServerUrl.Trim('/');
  757. }
  758. string smart = NetManager.GetBindAddress(hostname, out var port);
  759. return GetLocalApiUrl(smart.Trim('/'), null, port);
  760. }
  761. /// <inheritdoc/>
  762. public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
  763. {
  764. // With an empty source, the port will be null
  765. var smart = NetManager.GetBindAddress(ipAddress, out _, false);
  766. var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
  767. int? port = !allowHttps ? HttpPort : null;
  768. return GetLocalApiUrl(smart, scheme, port);
  769. }
  770. /// <inheritdoc/>
  771. public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
  772. {
  773. // If the smartAPI doesn't start with http then treat it as a host or ip.
  774. if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  775. {
  776. return hostname.TrimEnd('/');
  777. }
  778. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  779. // not. For consistency, always trim the trailing slash.
  780. scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
  781. var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
  782. return new UriBuilder
  783. {
  784. Scheme = scheme,
  785. Host = hostname,
  786. Port = port ?? (isHttps ? HttpsPort : HttpPort),
  787. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  788. }.ToString().TrimEnd('/');
  789. }
  790. public IEnumerable<Assembly> GetApiPluginAssemblies()
  791. {
  792. var assemblies = _allConcreteTypes
  793. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  794. .Select(i => i.Assembly)
  795. .Distinct();
  796. foreach (var assembly in assemblies)
  797. {
  798. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  799. yield return assembly;
  800. }
  801. }
  802. /// <inheritdoc />
  803. public void Dispose()
  804. {
  805. Dispose(true);
  806. GC.SuppressFinalize(this);
  807. }
  808. /// <summary>
  809. /// Releases unmanaged and - optionally - managed resources.
  810. /// </summary>
  811. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  812. protected virtual void Dispose(bool dispose)
  813. {
  814. if (_disposed)
  815. {
  816. return;
  817. }
  818. if (dispose)
  819. {
  820. var type = GetType();
  821. Logger.LogInformation("Disposing {Type}", type.Name);
  822. foreach (var (part, _) in _disposableParts)
  823. {
  824. var partType = part.GetType();
  825. if (partType == type)
  826. {
  827. continue;
  828. }
  829. Logger.LogInformation("Disposing {Type}", partType.Name);
  830. try
  831. {
  832. part.Dispose();
  833. }
  834. catch (Exception ex)
  835. {
  836. Logger.LogError(ex, "Error disposing {Type}", partType.Name);
  837. }
  838. }
  839. _disposableParts.Clear();
  840. }
  841. _disposed = true;
  842. }
  843. }
  844. }