ApplicationHost.cs 39 KB

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