ApplicationHost.cs 38 KB

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