ApplicationHost.cs 37 KB

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