ApplicationHost.cs 38 KB

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