ApplicationHost.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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. /// <returns>A task representing the service initialization operation.</returns>
  465. public async Task InitializeServices()
  466. {
  467. var jellyfinDb = await Resolve<IDbContextFactory<JellyfinDbContext>>().CreateDbContextAsync().ConfigureAwait(false);
  468. await using (jellyfinDb.ConfigureAwait(false))
  469. {
  470. if ((await jellyfinDb.Database.GetPendingMigrationsAsync().ConfigureAwait(false)).Any())
  471. {
  472. Logger.LogInformation("There are pending EFCore migrations in the database. Applying... (This may take a while, do not stop Jellyfin)");
  473. await jellyfinDb.Database.MigrateAsync().ConfigureAwait(false);
  474. Logger.LogInformation("EFCore migrations applied successfully");
  475. }
  476. }
  477. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  478. await localizationManager.LoadAll().ConfigureAwait(false);
  479. SetStaticProperties();
  480. FindParts();
  481. }
  482. private X509Certificate2 GetCertificate(string path, string password)
  483. {
  484. if (string.IsNullOrWhiteSpace(path))
  485. {
  486. return null;
  487. }
  488. try
  489. {
  490. if (!File.Exists(path))
  491. {
  492. return null;
  493. }
  494. // Don't use an empty string password
  495. password = string.IsNullOrWhiteSpace(password) ? null : password;
  496. var localCert = new X509Certificate2(path, password, X509KeyStorageFlags.UserKeySet);
  497. if (!localCert.HasPrivateKey)
  498. {
  499. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
  500. return null;
  501. }
  502. return localCert;
  503. }
  504. catch (Exception ex)
  505. {
  506. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
  507. return null;
  508. }
  509. }
  510. /// <summary>
  511. /// Dirty hacks.
  512. /// </summary>
  513. private void SetStaticProperties()
  514. {
  515. // For now there's no real way to inject these properly
  516. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  517. BaseItem.ConfigurationManager = ConfigurationManager;
  518. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  519. BaseItem.ProviderManager = Resolve<IProviderManager>();
  520. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  521. BaseItem.ItemRepository = Resolve<IItemRepository>();
  522. BaseItem.FileSystem = Resolve<IFileSystem>();
  523. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  524. BaseItem.ChannelManager = Resolve<IChannelManager>();
  525. Video.RecordingsManager = Resolve<IRecordingsManager>();
  526. Folder.UserViewManager = Resolve<IUserViewManager>();
  527. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  528. UserView.CollectionManager = Resolve<ICollectionManager>();
  529. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  530. BaseItem.MediaSegmentManager = Resolve<IMediaSegmentManager>();
  531. CollectionFolder.XmlSerializer = _xmlSerializer;
  532. CollectionFolder.ApplicationHost = this;
  533. }
  534. /// <summary>
  535. /// Finds plugin components and register them with the appropriate services.
  536. /// </summary>
  537. private void FindParts()
  538. {
  539. if (!ConfigurationManager.Configuration.IsPortAuthorized)
  540. {
  541. ConfigurationManager.Configuration.IsPortAuthorized = true;
  542. ConfigurationManager.SaveConfiguration();
  543. }
  544. _pluginManager.CreatePlugins();
  545. Resolve<ILibraryManager>().AddParts(
  546. GetExports<IResolverIgnoreRule>(),
  547. GetExports<IItemResolver>(),
  548. GetExports<IIntroProvider>(),
  549. GetExports<IBaseItemComparer>(),
  550. GetExports<ILibraryPostScanTask>());
  551. Resolve<IProviderManager>().AddParts(
  552. GetExports<IImageProvider>(),
  553. GetExports<IMetadataService>(),
  554. GetExports<IMetadataProvider>(),
  555. GetExports<IMetadataSaver>(),
  556. GetExports<IExternalId>(),
  557. GetExports<IExternalUrlProvider>());
  558. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  559. }
  560. /// <summary>
  561. /// Discovers the types.
  562. /// </summary>
  563. protected void DiscoverTypes()
  564. {
  565. Logger.LogInformation("Loading assemblies");
  566. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  567. }
  568. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  569. {
  570. foreach (var ass in assemblies)
  571. {
  572. Type[] exportedTypes;
  573. try
  574. {
  575. exportedTypes = ass.GetExportedTypes();
  576. }
  577. catch (FileNotFoundException ex)
  578. {
  579. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  580. _pluginManager.FailPlugin(ass);
  581. continue;
  582. }
  583. catch (TypeLoadException ex)
  584. {
  585. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  586. _pluginManager.FailPlugin(ass);
  587. continue;
  588. }
  589. foreach (Type type in exportedTypes)
  590. {
  591. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  592. {
  593. yield return type;
  594. }
  595. }
  596. }
  597. }
  598. /// <summary>
  599. /// Called when [configuration updated].
  600. /// </summary>
  601. /// <param name="sender">The sender.</param>
  602. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  603. private void OnConfigurationUpdated(object sender, EventArgs e)
  604. {
  605. var requiresRestart = false;
  606. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  607. // Don't do anything if these haven't been set yet
  608. if (HttpPort != 0 && HttpsPort != 0)
  609. {
  610. // Need to restart if ports have changed
  611. if (networkConfiguration.InternalHttpPort != HttpPort
  612. || networkConfiguration.InternalHttpsPort != HttpsPort)
  613. {
  614. if (ConfigurationManager.Configuration.IsPortAuthorized)
  615. {
  616. ConfigurationManager.Configuration.IsPortAuthorized = false;
  617. ConfigurationManager.SaveConfiguration();
  618. requiresRestart = true;
  619. }
  620. }
  621. }
  622. if (ValidateSslCertificate(networkConfiguration))
  623. {
  624. requiresRestart = true;
  625. }
  626. if (requiresRestart)
  627. {
  628. Logger.LogInformation("App needs to be restarted due to configuration change.");
  629. NotifyPendingRestart();
  630. }
  631. }
  632. /// <summary>
  633. /// Validates the SSL certificate.
  634. /// </summary>
  635. /// <param name="networkConfig">The new configuration.</param>
  636. /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
  637. private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
  638. {
  639. var newPath = networkConfig.CertificatePath;
  640. if (!string.IsNullOrWhiteSpace(newPath)
  641. && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
  642. {
  643. if (File.Exists(newPath))
  644. {
  645. return true;
  646. }
  647. throw new FileNotFoundException(
  648. string.Format(
  649. CultureInfo.InvariantCulture,
  650. "Certificate file '{0}' does not exist.",
  651. newPath));
  652. }
  653. return false;
  654. }
  655. /// <summary>
  656. /// Notifies the kernel that a change has been made that requires a restart.
  657. /// </summary>
  658. public void NotifyPendingRestart()
  659. {
  660. Logger.LogInformation("App needs to be restarted.");
  661. var changed = !HasPendingRestart;
  662. HasPendingRestart = true;
  663. if (changed)
  664. {
  665. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  666. }
  667. }
  668. /// <summary>
  669. /// Gets the composable part assemblies.
  670. /// </summary>
  671. /// <returns>IEnumerable{Assembly}.</returns>
  672. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  673. {
  674. foreach (var p in _pluginManager.LoadAssemblies())
  675. {
  676. yield return p;
  677. }
  678. // Include composable parts in the Model assembly
  679. yield return typeof(SystemInfo).Assembly;
  680. // Include composable parts in the Common assembly
  681. yield return typeof(IApplicationHost).Assembly;
  682. // Include composable parts in the Controller assembly
  683. yield return typeof(IServerApplicationHost).Assembly;
  684. // Include composable parts in the Providers assembly
  685. yield return typeof(ProviderManager).Assembly;
  686. // Include composable parts in the Photos assembly
  687. yield return typeof(PhotoProvider).Assembly;
  688. // Emby.Server implementations
  689. yield return typeof(InstallationManager).Assembly;
  690. // MediaEncoding
  691. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  692. // Local metadata
  693. yield return typeof(BoxSetXmlSaver).Assembly;
  694. // Xbmc
  695. yield return typeof(ArtistNfoProvider).Assembly;
  696. // Network
  697. yield return typeof(NetworkManager).Assembly;
  698. // Hls
  699. yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
  700. foreach (var i in GetAssembliesWithPartsInternal())
  701. {
  702. yield return i;
  703. }
  704. }
  705. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  706. /// <inheritdoc/>
  707. public string GetSmartApiUrl(IPAddress remoteAddr)
  708. {
  709. // Published server ends with a /
  710. if (!string.IsNullOrEmpty(PublishedServerUrl))
  711. {
  712. // Published server ends with a '/', so we need to remove it.
  713. return PublishedServerUrl.Trim('/');
  714. }
  715. string smart = NetManager.GetBindAddress(remoteAddr, out var port);
  716. return GetLocalApiUrl(smart.Trim('/'), null, port);
  717. }
  718. /// <inheritdoc/>
  719. public string GetSmartApiUrl(HttpRequest request)
  720. {
  721. // Return the host in the HTTP request as the API URL if not configured otherwise
  722. if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
  723. {
  724. int? requestPort = request.Host.Port;
  725. if (requestPort is null
  726. || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
  727. || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
  728. {
  729. requestPort = -1;
  730. }
  731. return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
  732. }
  733. return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
  734. }
  735. /// <inheritdoc/>
  736. public string GetSmartApiUrl(string hostname)
  737. {
  738. // Published server ends with a /
  739. if (!string.IsNullOrEmpty(PublishedServerUrl))
  740. {
  741. // Published server ends with a '/', so we need to remove it.
  742. return PublishedServerUrl.Trim('/');
  743. }
  744. string smart = NetManager.GetBindAddress(hostname, out var port);
  745. return GetLocalApiUrl(smart.Trim('/'), null, port);
  746. }
  747. /// <inheritdoc/>
  748. public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
  749. {
  750. // With an empty source, the port will be null
  751. var smart = NetManager.GetBindAddress(ipAddress, out _, false);
  752. var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
  753. int? port = !allowHttps ? HttpPort : null;
  754. return GetLocalApiUrl(smart, scheme, port);
  755. }
  756. /// <inheritdoc/>
  757. public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
  758. {
  759. // If the smartAPI doesn't start with http then treat it as a host or ip.
  760. if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  761. {
  762. return hostname.TrimEnd('/');
  763. }
  764. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  765. // not. For consistency, always trim the trailing slash.
  766. scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
  767. var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
  768. return new UriBuilder
  769. {
  770. Scheme = scheme,
  771. Host = hostname,
  772. Port = port ?? (isHttps ? HttpsPort : HttpPort),
  773. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  774. }.ToString().TrimEnd('/');
  775. }
  776. public IEnumerable<Assembly> GetApiPluginAssemblies()
  777. {
  778. var assemblies = _allConcreteTypes
  779. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  780. .Select(i => i.Assembly)
  781. .Distinct();
  782. foreach (var assembly in assemblies)
  783. {
  784. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  785. yield return assembly;
  786. }
  787. }
  788. /// <inheritdoc />
  789. public void Dispose()
  790. {
  791. Dispose(true);
  792. GC.SuppressFinalize(this);
  793. }
  794. /// <summary>
  795. /// Releases unmanaged and - optionally - managed resources.
  796. /// </summary>
  797. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  798. protected virtual void Dispose(bool dispose)
  799. {
  800. if (_disposed)
  801. {
  802. return;
  803. }
  804. if (dispose)
  805. {
  806. var type = GetType();
  807. Logger.LogInformation("Disposing {Type}", type.Name);
  808. foreach (var part in _disposableParts.ToArray())
  809. {
  810. var partType = part.GetType();
  811. if (partType == type)
  812. {
  813. continue;
  814. }
  815. Logger.LogInformation("Disposing {Type}", partType.Name);
  816. try
  817. {
  818. part.Dispose();
  819. }
  820. catch (Exception ex)
  821. {
  822. Logger.LogError(ex, "Error disposing {Type}", partType.Name);
  823. }
  824. }
  825. _disposableParts.Clear();
  826. }
  827. _disposed = true;
  828. }
  829. }
  830. }