ApplicationHost.cs 39 KB

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