ApplicationHost.cs 38 KB

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