ApplicationHost.cs 42 KB

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