ApplicationHost.cs 39 KB

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