ApplicationHost.cs 39 KB

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