ApplicationHost.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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 Jellyfin.Server.Implementations.MediaSegments;
  42. using MediaBrowser.Common;
  43. using MediaBrowser.Common.Configuration;
  44. using MediaBrowser.Common.Events;
  45. using MediaBrowser.Common.Net;
  46. using MediaBrowser.Common.Plugins;
  47. using MediaBrowser.Common.Updates;
  48. using MediaBrowser.Controller;
  49. using MediaBrowser.Controller.Channels;
  50. using MediaBrowser.Controller.Chapters;
  51. using MediaBrowser.Controller.ClientEvent;
  52. using MediaBrowser.Controller.Collections;
  53. using MediaBrowser.Controller.Configuration;
  54. using MediaBrowser.Controller.Drawing;
  55. using MediaBrowser.Controller.Dto;
  56. using MediaBrowser.Controller.Entities;
  57. using MediaBrowser.Controller.Library;
  58. using MediaBrowser.Controller.LiveTv;
  59. using MediaBrowser.Controller.Lyrics;
  60. using MediaBrowser.Controller.MediaEncoding;
  61. using MediaBrowser.Controller.Net;
  62. using MediaBrowser.Controller.Persistence;
  63. using MediaBrowser.Controller.Playlists;
  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 ConcurrentBag<IDisposable> _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 PluginManager _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.CreateLogger<DeviceId>());
  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.Add(_pluginManager);
  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.Add(part);
  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.Add(part);
  334. }
  335. }
  336. return parts;
  337. }
  338. /// <summary>
  339. /// Runs the startup tasks.
  340. /// </summary>
  341. /// <returns><see cref="Task" />.</returns>
  342. public 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. Logger.LogInformation("Core startup complete");
  351. CoreStartupHasCompleted = true;
  352. return Task.CompletedTask;
  353. }
  354. /// <inheritdoc/>
  355. public void Init(IServiceCollection serviceCollection)
  356. {
  357. DiscoverTypes();
  358. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  359. NetManager = new NetworkManager(ConfigurationManager, _startupConfig, LoggerFactory.CreateLogger<NetworkManager>());
  360. // Initialize runtime stat collection
  361. if (ConfigurationManager.Configuration.EnableMetrics)
  362. {
  363. _disposableParts.Add(DotNetRuntimeStatsBuilder.Default().StartCollecting());
  364. }
  365. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  366. HttpPort = networkConfiguration.InternalHttpPort;
  367. HttpsPort = networkConfiguration.InternalHttpsPort;
  368. // Safeguard against invalid configuration
  369. if (HttpPort == HttpsPort)
  370. {
  371. HttpPort = NetworkConfiguration.DefaultHttpPort;
  372. HttpsPort = NetworkConfiguration.DefaultHttpsPort;
  373. }
  374. CertificatePath = networkConfiguration.CertificatePath;
  375. Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword);
  376. RegisterServices(serviceCollection);
  377. _pluginManager.RegisterServices(serviceCollection);
  378. }
  379. /// <summary>
  380. /// Registers services/resources with the service collection that will be available via DI.
  381. /// </summary>
  382. /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
  383. protected virtual void RegisterServices(IServiceCollection serviceCollection)
  384. {
  385. serviceCollection.AddSingleton(_startupOptions);
  386. serviceCollection.AddMemoryCache();
  387. serviceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
  388. serviceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
  389. serviceCollection.AddSingleton<IApplicationHost>(this);
  390. serviceCollection.AddSingleton<IPluginManager>(_pluginManager);
  391. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  392. serviceCollection.AddSingleton<IFileSystem, ManagedFileSystem>();
  393. serviceCollection.AddSingleton<IShortcutHandler, MbLinkShortcutHandler>();
  394. serviceCollection.AddScoped<ISystemManager, SystemManager>();
  395. serviceCollection.AddSingleton<TmdbClientManager>();
  396. serviceCollection.AddSingleton(NetManager);
  397. serviceCollection.AddSingleton<ITaskManager, TaskManager>();
  398. serviceCollection.AddSingleton(_xmlSerializer);
  399. serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  400. serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  401. serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  402. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  403. serviceCollection.AddSingleton(ApplicationPaths);
  404. serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  405. serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  406. serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  407. serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  408. serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  409. serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  410. serviceCollection.AddSingleton<EncodingHelper>();
  411. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  412. serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  413. serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  414. serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  415. serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  416. serviceCollection.AddSingleton<NamingOptions>();
  417. serviceCollection.AddSingleton<IMusicManager, MusicManager>();
  418. serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  419. serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  420. serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  421. serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  422. serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  423. serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  424. serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  425. serviceCollection.AddSingleton<ILyricManager, LyricManager>();
  426. serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
  427. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  428. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  429. serviceCollection.AddSingleton<IDtoService, DtoService>();
  430. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  431. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  432. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  433. serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  434. serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  435. serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
  436. serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  437. serviceCollection.AddSingleton<IAuthService, AuthService>();
  438. serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  439. serviceCollection.AddSingleton<ISubtitleParser, SubtitleEditParser>();
  440. serviceCollection.AddSingleton<ISubtitleEncoder, SubtitleEncoder>();
  441. serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  442. serviceCollection.AddSingleton<ITranscodeManager, TranscodeManager>();
  443. serviceCollection.AddScoped<MediaInfoHelper>();
  444. serviceCollection.AddScoped<AudioHelper>();
  445. serviceCollection.AddScoped<DynamicHlsHelper>();
  446. serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>();
  447. serviceCollection.AddSingleton<IDirectoryService, DirectoryService>();
  448. serviceCollection.AddSingleton<IMediaSegmentManager, MediaSegmentManager>();
  449. }
  450. /// <summary>
  451. /// Create services registered with the service container that need to be initialized at application startup.
  452. /// </summary>
  453. /// <returns>A task representing the service initialization operation.</returns>
  454. public async Task InitializeServices()
  455. {
  456. var jellyfinDb = await Resolve<IDbContextFactory<JellyfinDbContext>>().CreateDbContextAsync().ConfigureAwait(false);
  457. await using (jellyfinDb.ConfigureAwait(false))
  458. {
  459. if ((await jellyfinDb.Database.GetPendingMigrationsAsync().ConfigureAwait(false)).Any())
  460. {
  461. Logger.LogInformation("There are pending EFCore migrations in the database. Applying... (This may take a while, do not stop Jellyfin)");
  462. await jellyfinDb.Database.MigrateAsync().ConfigureAwait(false);
  463. Logger.LogInformation("EFCore migrations applied successfully");
  464. }
  465. }
  466. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize();
  467. ((SqliteUserDataRepository)Resolve<IUserDataRepository>()).Initialize();
  468. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  469. await localizationManager.LoadAll().ConfigureAwait(false);
  470. SetStaticProperties();
  471. FindParts();
  472. }
  473. private X509Certificate2 GetCertificate(string path, string password)
  474. {
  475. if (string.IsNullOrWhiteSpace(path))
  476. {
  477. return null;
  478. }
  479. try
  480. {
  481. if (!File.Exists(path))
  482. {
  483. return null;
  484. }
  485. // Don't use an empty string password
  486. password = string.IsNullOrWhiteSpace(password) ? null : password;
  487. var localCert = new X509Certificate2(path, password, X509KeyStorageFlags.UserKeySet);
  488. if (!localCert.HasPrivateKey)
  489. {
  490. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
  491. return null;
  492. }
  493. return localCert;
  494. }
  495. catch (Exception ex)
  496. {
  497. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
  498. return null;
  499. }
  500. }
  501. /// <summary>
  502. /// Dirty hacks.
  503. /// </summary>
  504. private void SetStaticProperties()
  505. {
  506. // For now there's no real way to inject these properly
  507. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  508. BaseItem.ConfigurationManager = ConfigurationManager;
  509. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  510. BaseItem.ProviderManager = Resolve<IProviderManager>();
  511. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  512. BaseItem.ItemRepository = Resolve<IItemRepository>();
  513. BaseItem.FileSystem = Resolve<IFileSystem>();
  514. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  515. BaseItem.ChannelManager = Resolve<IChannelManager>();
  516. Video.RecordingsManager = Resolve<IRecordingsManager>();
  517. Folder.UserViewManager = Resolve<IUserViewManager>();
  518. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  519. UserView.CollectionManager = Resolve<ICollectionManager>();
  520. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  521. BaseItem.MediaSegmentManager = Resolve<IMediaSegmentManager>();
  522. CollectionFolder.XmlSerializer = _xmlSerializer;
  523. CollectionFolder.ApplicationHost = this;
  524. }
  525. /// <summary>
  526. /// Finds plugin components and register them with the appropriate services.
  527. /// </summary>
  528. private void FindParts()
  529. {
  530. if (!ConfigurationManager.Configuration.IsPortAuthorized)
  531. {
  532. ConfigurationManager.Configuration.IsPortAuthorized = true;
  533. ConfigurationManager.SaveConfiguration();
  534. }
  535. _pluginManager.CreatePlugins();
  536. Resolve<ILibraryManager>().AddParts(
  537. GetExports<IResolverIgnoreRule>(),
  538. GetExports<IItemResolver>(),
  539. GetExports<IIntroProvider>(),
  540. GetExports<IBaseItemComparer>(),
  541. GetExports<ILibraryPostScanTask>());
  542. Resolve<IProviderManager>().AddParts(
  543. GetExports<IImageProvider>(),
  544. GetExports<IMetadataService>(),
  545. GetExports<IMetadataProvider>(),
  546. GetExports<IMetadataSaver>(),
  547. GetExports<IExternalId>(),
  548. GetExports<IExternalUrlProvider>());
  549. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  550. }
  551. /// <summary>
  552. /// Discovers the types.
  553. /// </summary>
  554. protected void DiscoverTypes()
  555. {
  556. Logger.LogInformation("Loading assemblies");
  557. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  558. }
  559. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  560. {
  561. foreach (var ass in assemblies)
  562. {
  563. Type[] exportedTypes;
  564. try
  565. {
  566. exportedTypes = ass.GetExportedTypes();
  567. }
  568. catch (FileNotFoundException ex)
  569. {
  570. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  571. _pluginManager.FailPlugin(ass);
  572. continue;
  573. }
  574. catch (TypeLoadException ex)
  575. {
  576. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  577. _pluginManager.FailPlugin(ass);
  578. continue;
  579. }
  580. foreach (Type type in exportedTypes)
  581. {
  582. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  583. {
  584. yield return type;
  585. }
  586. }
  587. }
  588. }
  589. /// <summary>
  590. /// Called when [configuration updated].
  591. /// </summary>
  592. /// <param name="sender">The sender.</param>
  593. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  594. private void OnConfigurationUpdated(object sender, EventArgs e)
  595. {
  596. var requiresRestart = false;
  597. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  598. // Don't do anything if these haven't been set yet
  599. if (HttpPort != 0 && HttpsPort != 0)
  600. {
  601. // Need to restart if ports have changed
  602. if (networkConfiguration.InternalHttpPort != HttpPort
  603. || networkConfiguration.InternalHttpsPort != HttpsPort)
  604. {
  605. if (ConfigurationManager.Configuration.IsPortAuthorized)
  606. {
  607. ConfigurationManager.Configuration.IsPortAuthorized = false;
  608. ConfigurationManager.SaveConfiguration();
  609. requiresRestart = true;
  610. }
  611. }
  612. }
  613. if (ValidateSslCertificate(networkConfiguration))
  614. {
  615. requiresRestart = true;
  616. }
  617. if (requiresRestart)
  618. {
  619. Logger.LogInformation("App needs to be restarted due to configuration change.");
  620. NotifyPendingRestart();
  621. }
  622. }
  623. /// <summary>
  624. /// Validates the SSL certificate.
  625. /// </summary>
  626. /// <param name="networkConfig">The new configuration.</param>
  627. /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
  628. private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
  629. {
  630. var newPath = networkConfig.CertificatePath;
  631. if (!string.IsNullOrWhiteSpace(newPath)
  632. && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
  633. {
  634. if (File.Exists(newPath))
  635. {
  636. return true;
  637. }
  638. throw new FileNotFoundException(
  639. string.Format(
  640. CultureInfo.InvariantCulture,
  641. "Certificate file '{0}' does not exist.",
  642. newPath));
  643. }
  644. return false;
  645. }
  646. /// <summary>
  647. /// Notifies the kernel that a change has been made that requires a restart.
  648. /// </summary>
  649. public void NotifyPendingRestart()
  650. {
  651. Logger.LogInformation("App needs to be restarted.");
  652. var changed = !HasPendingRestart;
  653. HasPendingRestart = true;
  654. if (changed)
  655. {
  656. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  657. }
  658. }
  659. /// <summary>
  660. /// Gets the composable part assemblies.
  661. /// </summary>
  662. /// <returns>IEnumerable{Assembly}.</returns>
  663. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  664. {
  665. foreach (var p in _pluginManager.LoadAssemblies())
  666. {
  667. yield return p;
  668. }
  669. // Include composable parts in the Model assembly
  670. yield return typeof(SystemInfo).Assembly;
  671. // Include composable parts in the Common assembly
  672. yield return typeof(IApplicationHost).Assembly;
  673. // Include composable parts in the Controller assembly
  674. yield return typeof(IServerApplicationHost).Assembly;
  675. // Include composable parts in the Providers assembly
  676. yield return typeof(ProviderManager).Assembly;
  677. // Include composable parts in the Photos assembly
  678. yield return typeof(PhotoProvider).Assembly;
  679. // Emby.Server implementations
  680. yield return typeof(InstallationManager).Assembly;
  681. // MediaEncoding
  682. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  683. // Local metadata
  684. yield return typeof(BoxSetXmlSaver).Assembly;
  685. // Xbmc
  686. yield return typeof(ArtistNfoProvider).Assembly;
  687. // Network
  688. yield return typeof(NetworkManager).Assembly;
  689. // Hls
  690. yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
  691. foreach (var i in GetAssembliesWithPartsInternal())
  692. {
  693. yield return i;
  694. }
  695. }
  696. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  697. /// <inheritdoc/>
  698. public string GetSmartApiUrl(IPAddress remoteAddr)
  699. {
  700. // Published server ends with a /
  701. if (!string.IsNullOrEmpty(PublishedServerUrl))
  702. {
  703. // Published server ends with a '/', so we need to remove it.
  704. return PublishedServerUrl.Trim('/');
  705. }
  706. string smart = NetManager.GetBindAddress(remoteAddr, out var port);
  707. return GetLocalApiUrl(smart.Trim('/'), null, port);
  708. }
  709. /// <inheritdoc/>
  710. public string GetSmartApiUrl(HttpRequest request)
  711. {
  712. // Return the host in the HTTP request as the API URL if not configured otherwise
  713. if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
  714. {
  715. int? requestPort = request.Host.Port;
  716. if (requestPort is null
  717. || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
  718. || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
  719. {
  720. requestPort = -1;
  721. }
  722. return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
  723. }
  724. return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
  725. }
  726. /// <inheritdoc/>
  727. public string GetSmartApiUrl(string hostname)
  728. {
  729. // Published server ends with a /
  730. if (!string.IsNullOrEmpty(PublishedServerUrl))
  731. {
  732. // Published server ends with a '/', so we need to remove it.
  733. return PublishedServerUrl.Trim('/');
  734. }
  735. string smart = NetManager.GetBindAddress(hostname, out var port);
  736. return GetLocalApiUrl(smart.Trim('/'), null, port);
  737. }
  738. /// <inheritdoc/>
  739. public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
  740. {
  741. // With an empty source, the port will be null
  742. var smart = NetManager.GetBindAddress(ipAddress, out _, false);
  743. var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
  744. int? port = !allowHttps ? HttpPort : null;
  745. return GetLocalApiUrl(smart, scheme, port);
  746. }
  747. /// <inheritdoc/>
  748. public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
  749. {
  750. // If the smartAPI doesn't start with http then treat it as a host or ip.
  751. if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  752. {
  753. return hostname.TrimEnd('/');
  754. }
  755. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  756. // not. For consistency, always trim the trailing slash.
  757. scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
  758. var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
  759. return new UriBuilder
  760. {
  761. Scheme = scheme,
  762. Host = hostname,
  763. Port = port ?? (isHttps ? HttpsPort : HttpPort),
  764. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  765. }.ToString().TrimEnd('/');
  766. }
  767. public IEnumerable<Assembly> GetApiPluginAssemblies()
  768. {
  769. var assemblies = _allConcreteTypes
  770. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  771. .Select(i => i.Assembly)
  772. .Distinct();
  773. foreach (var assembly in assemblies)
  774. {
  775. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  776. yield return assembly;
  777. }
  778. }
  779. /// <inheritdoc />
  780. public void Dispose()
  781. {
  782. Dispose(true);
  783. GC.SuppressFinalize(this);
  784. }
  785. /// <summary>
  786. /// Releases unmanaged and - optionally - managed resources.
  787. /// </summary>
  788. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  789. protected virtual void Dispose(bool dispose)
  790. {
  791. if (_disposed)
  792. {
  793. return;
  794. }
  795. if (dispose)
  796. {
  797. var type = GetType();
  798. Logger.LogInformation("Disposing {Type}", type.Name);
  799. foreach (var part in _disposableParts.ToArray())
  800. {
  801. var partType = part.GetType();
  802. if (partType == type)
  803. {
  804. continue;
  805. }
  806. Logger.LogInformation("Disposing {Type}", partType.Name);
  807. try
  808. {
  809. part.Dispose();
  810. }
  811. catch (Exception ex)
  812. {
  813. Logger.LogError(ex, "Error disposing {Type}", partType.Name);
  814. }
  815. }
  816. _disposableParts.Clear();
  817. }
  818. _disposed = true;
  819. }
  820. }
  821. }