ApplicationHost.cs 39 KB

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