ApplicationHost.cs 38 KB

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