ApplicationHost.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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.Channels;
  17. using Emby.Server.Implementations.Collections;
  18. using Emby.Server.Implementations.Configuration;
  19. using Emby.Server.Implementations.Cryptography;
  20. using Emby.Server.Implementations.Data;
  21. using Emby.Server.Implementations.Devices;
  22. using Emby.Server.Implementations.Dto;
  23. using Emby.Server.Implementations.HttpServer.Security;
  24. using Emby.Server.Implementations.IO;
  25. using Emby.Server.Implementations.Library;
  26. using Emby.Server.Implementations.Localization;
  27. using Emby.Server.Implementations.Playlists;
  28. using Emby.Server.Implementations.Plugins;
  29. using Emby.Server.Implementations.QuickConnect;
  30. using Emby.Server.Implementations.ScheduledTasks;
  31. using Emby.Server.Implementations.Serialization;
  32. using Emby.Server.Implementations.Session;
  33. using Emby.Server.Implementations.SyncPlay;
  34. using Emby.Server.Implementations.TV;
  35. using Emby.Server.Implementations.Updates;
  36. using Jellyfin.Api.Helpers;
  37. using Jellyfin.Drawing;
  38. using Jellyfin.MediaEncoding.Hls.Playlist;
  39. using Jellyfin.Networking.Manager;
  40. using Jellyfin.Networking.Udp;
  41. using Jellyfin.Server.Implementations;
  42. using MediaBrowser.Common;
  43. using MediaBrowser.Common.Configuration;
  44. using MediaBrowser.Common.Events;
  45. using MediaBrowser.Common.Net;
  46. using MediaBrowser.Common.Plugins;
  47. using MediaBrowser.Common.Updates;
  48. using MediaBrowser.Controller;
  49. using MediaBrowser.Controller.Channels;
  50. using MediaBrowser.Controller.Chapters;
  51. using MediaBrowser.Controller.ClientEvent;
  52. using MediaBrowser.Controller.Collections;
  53. using MediaBrowser.Controller.Configuration;
  54. using MediaBrowser.Controller.Drawing;
  55. using MediaBrowser.Controller.Dto;
  56. using MediaBrowser.Controller.Entities;
  57. using MediaBrowser.Controller.Library;
  58. using MediaBrowser.Controller.LiveTv;
  59. using MediaBrowser.Controller.Lyrics;
  60. using MediaBrowser.Controller.MediaEncoding;
  61. using MediaBrowser.Controller.Net;
  62. using MediaBrowser.Controller.Persistence;
  63. using MediaBrowser.Controller.Playlists;
  64. using MediaBrowser.Controller.Plugins;
  65. using MediaBrowser.Controller.Providers;
  66. using MediaBrowser.Controller.QuickConnect;
  67. using MediaBrowser.Controller.Resolvers;
  68. using MediaBrowser.Controller.Session;
  69. using MediaBrowser.Controller.Sorting;
  70. using MediaBrowser.Controller.Subtitles;
  71. using MediaBrowser.Controller.SyncPlay;
  72. using MediaBrowser.Controller.TV;
  73. using MediaBrowser.LocalMetadata.Savers;
  74. using MediaBrowser.MediaEncoding.BdInfo;
  75. using MediaBrowser.MediaEncoding.Subtitles;
  76. using MediaBrowser.MediaEncoding.Transcoding;
  77. using MediaBrowser.Model.Cryptography;
  78. using MediaBrowser.Model.Globalization;
  79. using MediaBrowser.Model.IO;
  80. using MediaBrowser.Model.MediaInfo;
  81. using MediaBrowser.Model.Net;
  82. using MediaBrowser.Model.Serialization;
  83. using MediaBrowser.Model.System;
  84. using MediaBrowser.Model.Tasks;
  85. using MediaBrowser.Providers.Chapters;
  86. using MediaBrowser.Providers.Lyric;
  87. using MediaBrowser.Providers.Manager;
  88. using MediaBrowser.Providers.Plugins.Tmdb;
  89. using MediaBrowser.Providers.Subtitles;
  90. using MediaBrowser.XbmcMetadata.Providers;
  91. using Microsoft.AspNetCore.Http;
  92. using Microsoft.AspNetCore.Mvc;
  93. using Microsoft.EntityFrameworkCore;
  94. using Microsoft.Extensions.Configuration;
  95. using Microsoft.Extensions.DependencyInjection;
  96. using Microsoft.Extensions.Logging;
  97. using Prometheus.DotNetRuntime;
  98. using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
  99. using IConfigurationManager = MediaBrowser.Common.Configuration.IConfigurationManager;
  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 ServiceProvider is null
  268. ? Activator.CreateInstance(type)
  269. : ActivatorUtilities.CreateInstance(ServiceProvider, type);
  270. }
  271. catch (Exception ex)
  272. {
  273. Logger.LogError(ex, "Error creating {Type}", type);
  274. // If this is a plugin fail it.
  275. _pluginManager.FailPlugin(type.Assembly);
  276. return null;
  277. }
  278. finally
  279. {
  280. _creatingInstances.Remove(type);
  281. }
  282. }
  283. /// <summary>
  284. /// Resolves this instance.
  285. /// </summary>
  286. /// <typeparam name="T">The type.</typeparam>
  287. /// <returns>``0.</returns>
  288. public T Resolve<T>() => ServiceProvider.GetService<T>();
  289. /// <inheritdoc/>
  290. public IEnumerable<Type> GetExportTypes<T>()
  291. {
  292. var currentType = typeof(T);
  293. var numberOfConcreteTypes = _allConcreteTypes.Length;
  294. for (var i = 0; i < numberOfConcreteTypes; i++)
  295. {
  296. var type = _allConcreteTypes[i];
  297. if (currentType.IsAssignableFrom(type))
  298. {
  299. yield return type;
  300. }
  301. }
  302. }
  303. /// <inheritdoc />
  304. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  305. {
  306. // Convert to list so this isn't executed for each iteration
  307. var parts = GetExportTypes<T>()
  308. .Select(CreateInstanceSafe)
  309. .Where(i => i is not null)
  310. .Cast<T>()
  311. .ToList();
  312. if (manageLifetime)
  313. {
  314. foreach (var part in parts.OfType<IDisposable>())
  315. {
  316. _disposableParts.TryAdd(part, byte.MinValue);
  317. }
  318. }
  319. return parts;
  320. }
  321. /// <inheritdoc />
  322. public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
  323. {
  324. // Convert to list so this isn't executed for each iteration
  325. var parts = GetExportTypes<T>()
  326. .Select(i => defaultFunc(i))
  327. .Where(i => i is not null)
  328. .Cast<T>()
  329. .ToList();
  330. if (manageLifetime)
  331. {
  332. foreach (var part in parts.OfType<IDisposable>())
  333. {
  334. _disposableParts.TryAdd(part, byte.MinValue);
  335. }
  336. }
  337. return parts;
  338. }
  339. /// <summary>
  340. /// Runs the startup tasks.
  341. /// </summary>
  342. /// <returns><see cref="Task" />.</returns>
  343. public async Task RunStartupTasksAsync()
  344. {
  345. Logger.LogInformation("Running startup tasks");
  346. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  347. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  348. ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
  349. Resolve<IMediaEncoder>().SetFFmpegPath();
  350. Logger.LogInformation("ServerId: {ServerId}", SystemId);
  351. var entryPoints = GetExports<IServerEntryPoint>();
  352. var stopWatch = new Stopwatch();
  353. stopWatch.Start();
  354. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  355. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  356. Logger.LogInformation("Core startup complete");
  357. CoreStartupHasCompleted = true;
  358. stopWatch.Restart();
  359. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  360. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  361. stopWatch.Stop();
  362. }
  363. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  364. {
  365. foreach (var entryPoint in entryPoints)
  366. {
  367. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  368. {
  369. continue;
  370. }
  371. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  372. yield return entryPoint.RunAsync();
  373. }
  374. }
  375. /// <inheritdoc/>
  376. public void Init(IServiceCollection serviceCollection)
  377. {
  378. DiscoverTypes();
  379. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  380. NetManager = new NetworkManager(ConfigurationManager, _startupConfig, LoggerFactory.CreateLogger<NetworkManager>());
  381. // Initialize runtime stat collection
  382. if (ConfigurationManager.Configuration.EnableMetrics)
  383. {
  384. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  385. }
  386. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  387. HttpPort = networkConfiguration.InternalHttpPort;
  388. HttpsPort = networkConfiguration.InternalHttpsPort;
  389. // Safeguard against invalid configuration
  390. if (HttpPort == HttpsPort)
  391. {
  392. HttpPort = NetworkConfiguration.DefaultHttpPort;
  393. HttpsPort = NetworkConfiguration.DefaultHttpsPort;
  394. }
  395. CertificatePath = networkConfiguration.CertificatePath;
  396. Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword);
  397. RegisterServices(serviceCollection);
  398. _pluginManager.RegisterServices(serviceCollection);
  399. }
  400. /// <summary>
  401. /// Registers services/resources with the service collection that will be available via DI.
  402. /// </summary>
  403. /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
  404. protected virtual void RegisterServices(IServiceCollection serviceCollection)
  405. {
  406. serviceCollection.AddSingleton(_startupOptions);
  407. serviceCollection.AddMemoryCache();
  408. serviceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
  409. serviceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
  410. serviceCollection.AddSingleton<IApplicationHost>(this);
  411. serviceCollection.AddSingleton(_pluginManager);
  412. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  413. serviceCollection.AddSingleton<IFileSystem, ManagedFileSystem>();
  414. serviceCollection.AddSingleton<IShortcutHandler, MbLinkShortcutHandler>();
  415. serviceCollection.AddScoped<ISystemManager, SystemManager>();
  416. serviceCollection.AddSingleton<TmdbClientManager>();
  417. serviceCollection.AddSingleton(NetManager);
  418. serviceCollection.AddSingleton<ITaskManager, TaskManager>();
  419. serviceCollection.AddSingleton(_xmlSerializer);
  420. serviceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  421. serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  422. serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  423. serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  424. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  425. serviceCollection.AddSingleton(ApplicationPaths);
  426. serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  427. serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  428. serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  429. serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  430. serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  431. serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  432. serviceCollection.AddSingleton<EncodingHelper>();
  433. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  434. serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  435. serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  436. serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  437. serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  438. serviceCollection.AddSingleton<NamingOptions>();
  439. serviceCollection.AddSingleton<IMusicManager, MusicManager>();
  440. serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  441. serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  442. serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  443. serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  444. serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  445. serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  446. serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  447. serviceCollection.AddSingleton<ILyricManager, LyricManager>();
  448. serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
  449. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  450. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  451. serviceCollection.AddSingleton<IDtoService, DtoService>();
  452. serviceCollection.AddSingleton<IChannelManager, ChannelManager>();
  453. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  454. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  455. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  456. serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  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<ITranscodeManager, TranscodeManager>();
  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. // Local metadata
  705. yield return typeof(BoxSetXmlSaver).Assembly;
  706. // Xbmc
  707. yield return typeof(ArtistNfoProvider).Assembly;
  708. // Network
  709. yield return typeof(NetworkManager).Assembly;
  710. // Hls
  711. yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
  712. foreach (var i in GetAssembliesWithPartsInternal())
  713. {
  714. yield return i;
  715. }
  716. }
  717. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  718. /// <inheritdoc/>
  719. public string GetSmartApiUrl(IPAddress remoteAddr)
  720. {
  721. // Published server ends with a /
  722. if (!string.IsNullOrEmpty(PublishedServerUrl))
  723. {
  724. // Published server ends with a '/', so we need to remove it.
  725. return PublishedServerUrl.Trim('/');
  726. }
  727. string smart = NetManager.GetBindAddress(remoteAddr, out var port);
  728. return GetLocalApiUrl(smart.Trim('/'), null, port);
  729. }
  730. /// <inheritdoc/>
  731. public string GetSmartApiUrl(HttpRequest request)
  732. {
  733. // Return the host in the HTTP request as the API URL if not configured otherwise
  734. if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
  735. {
  736. int? requestPort = request.Host.Port;
  737. if (requestPort is null
  738. || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
  739. || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
  740. {
  741. requestPort = -1;
  742. }
  743. return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
  744. }
  745. return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
  746. }
  747. /// <inheritdoc/>
  748. public string GetSmartApiUrl(string hostname)
  749. {
  750. // Published server ends with a /
  751. if (!string.IsNullOrEmpty(PublishedServerUrl))
  752. {
  753. // Published server ends with a '/', so we need to remove it.
  754. return PublishedServerUrl.Trim('/');
  755. }
  756. string smart = NetManager.GetBindAddress(hostname, out var port);
  757. return GetLocalApiUrl(smart.Trim('/'), null, port);
  758. }
  759. /// <inheritdoc/>
  760. public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
  761. {
  762. // With an empty source, the port will be null
  763. var smart = NetManager.GetBindAddress(ipAddress, out _, false);
  764. var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
  765. int? port = !allowHttps ? HttpPort : null;
  766. return GetLocalApiUrl(smart, scheme, port);
  767. }
  768. /// <inheritdoc/>
  769. public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
  770. {
  771. // If the smartAPI doesn't start with http then treat it as a host or ip.
  772. if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  773. {
  774. return hostname.TrimEnd('/');
  775. }
  776. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  777. // not. For consistency, always trim the trailing slash.
  778. scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
  779. var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
  780. return new UriBuilder
  781. {
  782. Scheme = scheme,
  783. Host = hostname,
  784. Port = port ?? (isHttps ? HttpsPort : HttpPort),
  785. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  786. }.ToString().TrimEnd('/');
  787. }
  788. public IEnumerable<Assembly> GetApiPluginAssemblies()
  789. {
  790. var assemblies = _allConcreteTypes
  791. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  792. .Select(i => i.Assembly)
  793. .Distinct();
  794. foreach (var assembly in assemblies)
  795. {
  796. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  797. yield return assembly;
  798. }
  799. }
  800. /// <inheritdoc />
  801. public void Dispose()
  802. {
  803. Dispose(true);
  804. GC.SuppressFinalize(this);
  805. }
  806. /// <summary>
  807. /// Releases unmanaged and - optionally - managed resources.
  808. /// </summary>
  809. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  810. protected virtual void Dispose(bool dispose)
  811. {
  812. if (_disposed)
  813. {
  814. return;
  815. }
  816. if (dispose)
  817. {
  818. var type = GetType();
  819. Logger.LogInformation("Disposing {Type}", type.Name);
  820. foreach (var (part, _) in _disposableParts)
  821. {
  822. var partType = part.GetType();
  823. if (partType == type)
  824. {
  825. continue;
  826. }
  827. Logger.LogInformation("Disposing {Type}", partType.Name);
  828. try
  829. {
  830. part.Dispose();
  831. }
  832. catch (Exception ex)
  833. {
  834. Logger.LogError(ex, "Error disposing {Type}", partType.Name);
  835. }
  836. }
  837. _disposableParts.Clear();
  838. }
  839. _disposed = true;
  840. }
  841. }
  842. }