ApplicationHost.cs 38 KB

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