ApplicationHost.cs 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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.Chapters;
  17. using Emby.Server.Implementations.Collections;
  18. using Emby.Server.Implementations.Configuration;
  19. using Emby.Server.Implementations.Cryptography;
  20. using Emby.Server.Implementations.Data;
  21. using Emby.Server.Implementations.Devices;
  22. using Emby.Server.Implementations.Dto;
  23. using Emby.Server.Implementations.HttpServer.Security;
  24. using Emby.Server.Implementations.IO;
  25. using Emby.Server.Implementations.Library;
  26. using Emby.Server.Implementations.Localization;
  27. using Emby.Server.Implementations.Playlists;
  28. using Emby.Server.Implementations.Plugins;
  29. using Emby.Server.Implementations.QuickConnect;
  30. using Emby.Server.Implementations.ScheduledTasks;
  31. using Emby.Server.Implementations.Serialization;
  32. using Emby.Server.Implementations.Session;
  33. using Emby.Server.Implementations.SyncPlay;
  34. using Emby.Server.Implementations.TV;
  35. using Emby.Server.Implementations.Updates;
  36. using Jellyfin.Api.Helpers;
  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.MediaSegments;
  64. using MediaBrowser.Controller.Net;
  65. using MediaBrowser.Controller.Persistence;
  66. using MediaBrowser.Controller.Playlists;
  67. using MediaBrowser.Controller.Providers;
  68. using MediaBrowser.Controller.QuickConnect;
  69. using MediaBrowser.Controller.Resolvers;
  70. using MediaBrowser.Controller.Session;
  71. using MediaBrowser.Controller.Sorting;
  72. using MediaBrowser.Controller.Subtitles;
  73. using MediaBrowser.Controller.SyncPlay;
  74. using MediaBrowser.Controller.TV;
  75. using MediaBrowser.LocalMetadata.Savers;
  76. using MediaBrowser.MediaEncoding.BdInfo;
  77. using MediaBrowser.MediaEncoding.Subtitles;
  78. using MediaBrowser.MediaEncoding.Transcoding;
  79. using MediaBrowser.Model.Cryptography;
  80. using MediaBrowser.Model.Globalization;
  81. using MediaBrowser.Model.IO;
  82. using MediaBrowser.Model.MediaInfo;
  83. using MediaBrowser.Model.Net;
  84. using MediaBrowser.Model.Serialization;
  85. using MediaBrowser.Model.System;
  86. using MediaBrowser.Model.Tasks;
  87. using MediaBrowser.Providers.Lyric;
  88. using MediaBrowser.Providers.Manager;
  89. using MediaBrowser.Providers.Plugins.Tmdb;
  90. using MediaBrowser.Providers.Subtitles;
  91. using MediaBrowser.XbmcMetadata.Providers;
  92. using Microsoft.AspNetCore.Http;
  93. using Microsoft.AspNetCore.Mvc;
  94. using Microsoft.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<IKeyframeRepository, KeyframeRepository>();
  422. serviceCollection.AddSingleton<IItemTypeLookup, ItemTypeLookup>();
  423. serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  424. serviceCollection.AddSingleton<EncodingHelper>();
  425. serviceCollection.AddSingleton<IPathManager, PathManager>();
  426. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  427. serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  428. serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  429. serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  430. serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  431. serviceCollection.AddSingleton<NamingOptions>();
  432. serviceCollection.AddSingleton<IMusicManager, MusicManager>();
  433. serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  434. serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  435. serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  436. serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  437. serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  438. serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  439. serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  440. serviceCollection.AddSingleton<ILyricManager, LyricManager>();
  441. serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
  442. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  443. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  444. serviceCollection.AddSingleton<IDtoService, DtoService>();
  445. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  446. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  447. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  448. serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  449. serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  450. serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
  451. serviceCollection.AddSingleton<IAuthService, AuthService>();
  452. serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  453. serviceCollection.AddSingleton<ISubtitleParser, SubtitleEditParser>();
  454. serviceCollection.AddSingleton<ISubtitleEncoder, SubtitleEncoder>();
  455. serviceCollection.AddSingleton<IKeyframeManager, KeyframeManager>();
  456. serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  457. serviceCollection.AddSingleton<ITranscodeManager, TranscodeManager>();
  458. serviceCollection.AddScoped<MediaInfoHelper>();
  459. serviceCollection.AddScoped<AudioHelper>();
  460. serviceCollection.AddScoped<DynamicHlsHelper>();
  461. serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>();
  462. serviceCollection.AddSingleton<IDirectoryService, DirectoryService>();
  463. serviceCollection.AddSingleton<IMediaSegmentManager, MediaSegmentManager>();
  464. }
  465. /// <summary>
  466. /// Create services registered with the service container that need to be initialized at application startup.
  467. /// </summary>
  468. /// <param name="startupConfig">The configuration used to initialise the application.</param>
  469. /// <returns>A task representing the service initialization operation.</returns>
  470. public async Task InitializeServices(IConfiguration startupConfig)
  471. {
  472. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  473. await localizationManager.LoadAll().ConfigureAwait(false);
  474. SetStaticProperties();
  475. FindParts();
  476. }
  477. private X509Certificate2 GetCertificate(string path, string password)
  478. {
  479. if (string.IsNullOrWhiteSpace(path))
  480. {
  481. return null;
  482. }
  483. try
  484. {
  485. if (!File.Exists(path))
  486. {
  487. return null;
  488. }
  489. // Don't use an empty string password
  490. password = string.IsNullOrWhiteSpace(password) ? null : password;
  491. var localCert = X509CertificateLoader.LoadPkcs12FromFile(path, password, X509KeyStorageFlags.UserKeySet);
  492. if (!localCert.HasPrivateKey)
  493. {
  494. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
  495. return null;
  496. }
  497. return localCert;
  498. }
  499. catch (Exception ex)
  500. {
  501. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
  502. return null;
  503. }
  504. }
  505. /// <summary>
  506. /// Dirty hacks.
  507. /// </summary>
  508. private void SetStaticProperties()
  509. {
  510. // For now there's no real way to inject these properly
  511. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  512. BaseItem.ConfigurationManager = ConfigurationManager;
  513. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  514. BaseItem.ProviderManager = Resolve<IProviderManager>();
  515. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  516. BaseItem.ItemRepository = Resolve<IItemRepository>();
  517. BaseItem.ChapterManager = Resolve<IChapterManager>();
  518. BaseItem.FileSystem = Resolve<IFileSystem>();
  519. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  520. BaseItem.ChannelManager = Resolve<IChannelManager>();
  521. Video.RecordingsManager = Resolve<IRecordingsManager>();
  522. Folder.UserViewManager = Resolve<IUserViewManager>();
  523. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  524. UserView.CollectionManager = Resolve<ICollectionManager>();
  525. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  526. BaseItem.MediaSegmentManager = Resolve<IMediaSegmentManager>();
  527. CollectionFolder.XmlSerializer = _xmlSerializer;
  528. CollectionFolder.ApplicationHost = this;
  529. }
  530. /// <summary>
  531. /// Finds plugin components and register them with the appropriate services.
  532. /// </summary>
  533. private void FindParts()
  534. {
  535. if (!ConfigurationManager.Configuration.IsPortAuthorized)
  536. {
  537. ConfigurationManager.Configuration.IsPortAuthorized = true;
  538. ConfigurationManager.SaveConfiguration();
  539. }
  540. _pluginManager.CreatePlugins();
  541. Resolve<ILibraryManager>().AddParts(
  542. GetExports<IResolverIgnoreRule>(),
  543. GetExports<IItemResolver>(),
  544. GetExports<IIntroProvider>(),
  545. GetExports<IBaseItemComparer>(),
  546. GetExports<ILibraryPostScanTask>());
  547. Resolve<IProviderManager>().AddParts(
  548. GetExports<IImageProvider>(),
  549. GetExports<IMetadataService>(),
  550. GetExports<IMetadataProvider>(),
  551. GetExports<IMetadataSaver>(),
  552. GetExports<IExternalId>(),
  553. GetExports<IExternalUrlProvider>());
  554. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  555. }
  556. /// <summary>
  557. /// Discovers the types.
  558. /// </summary>
  559. protected void DiscoverTypes()
  560. {
  561. Logger.LogInformation("Loading assemblies");
  562. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  563. }
  564. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  565. {
  566. foreach (var ass in assemblies)
  567. {
  568. Type[] exportedTypes;
  569. try
  570. {
  571. exportedTypes = ass.GetExportedTypes();
  572. }
  573. catch (FileNotFoundException ex)
  574. {
  575. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  576. _pluginManager.FailPlugin(ass);
  577. continue;
  578. }
  579. catch (TypeLoadException ex)
  580. {
  581. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  582. _pluginManager.FailPlugin(ass);
  583. continue;
  584. }
  585. foreach (Type type in exportedTypes)
  586. {
  587. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  588. {
  589. yield return type;
  590. }
  591. }
  592. }
  593. }
  594. /// <summary>
  595. /// Called when [configuration updated].
  596. /// </summary>
  597. /// <param name="sender">The sender.</param>
  598. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  599. private void OnConfigurationUpdated(object sender, EventArgs e)
  600. {
  601. var requiresRestart = false;
  602. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  603. // Don't do anything if these haven't been set yet
  604. if (HttpPort != 0 && HttpsPort != 0)
  605. {
  606. // Need to restart if ports have changed
  607. if (networkConfiguration.InternalHttpPort != HttpPort
  608. || networkConfiguration.InternalHttpsPort != HttpsPort)
  609. {
  610. if (ConfigurationManager.Configuration.IsPortAuthorized)
  611. {
  612. ConfigurationManager.Configuration.IsPortAuthorized = false;
  613. ConfigurationManager.SaveConfiguration();
  614. requiresRestart = true;
  615. }
  616. }
  617. }
  618. if (ValidateSslCertificate(networkConfiguration))
  619. {
  620. requiresRestart = true;
  621. }
  622. if (requiresRestart)
  623. {
  624. Logger.LogInformation("App needs to be restarted due to configuration change.");
  625. NotifyPendingRestart();
  626. }
  627. }
  628. /// <summary>
  629. /// Validates the SSL certificate.
  630. /// </summary>
  631. /// <param name="networkConfig">The new configuration.</param>
  632. /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
  633. private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
  634. {
  635. var newPath = networkConfig.CertificatePath;
  636. if (!string.IsNullOrWhiteSpace(newPath)
  637. && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
  638. {
  639. if (File.Exists(newPath))
  640. {
  641. return true;
  642. }
  643. throw new FileNotFoundException(
  644. string.Format(
  645. CultureInfo.InvariantCulture,
  646. "Certificate file '{0}' does not exist.",
  647. newPath));
  648. }
  649. return false;
  650. }
  651. /// <summary>
  652. /// Notifies the kernel that a change has been made that requires a restart.
  653. /// </summary>
  654. public void NotifyPendingRestart()
  655. {
  656. Logger.LogInformation("App needs to be restarted.");
  657. var changed = !HasPendingRestart;
  658. HasPendingRestart = true;
  659. if (changed)
  660. {
  661. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  662. }
  663. }
  664. /// <summary>
  665. /// Gets the composable part assemblies.
  666. /// </summary>
  667. /// <returns>IEnumerable{Assembly}.</returns>
  668. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  669. {
  670. foreach (var p in _pluginManager.LoadAssemblies())
  671. {
  672. yield return p;
  673. }
  674. // Include composable parts in the Model assembly
  675. yield return typeof(SystemInfo).Assembly;
  676. // Include composable parts in the Common assembly
  677. yield return typeof(IApplicationHost).Assembly;
  678. // Include composable parts in the Controller assembly
  679. yield return typeof(IServerApplicationHost).Assembly;
  680. // Include composable parts in the Providers assembly
  681. yield return typeof(ProviderManager).Assembly;
  682. // Include composable parts in the Photos assembly
  683. yield return typeof(PhotoProvider).Assembly;
  684. // Emby.Server implementations
  685. yield return typeof(InstallationManager).Assembly;
  686. // MediaEncoding
  687. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  688. // Local metadata
  689. yield return typeof(BoxSetXmlSaver).Assembly;
  690. // Xbmc
  691. yield return typeof(ArtistNfoProvider).Assembly;
  692. // Network
  693. yield return typeof(NetworkManager).Assembly;
  694. // Hls
  695. yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
  696. foreach (var i in GetAssembliesWithPartsInternal())
  697. {
  698. yield return i;
  699. }
  700. }
  701. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  702. /// <inheritdoc/>
  703. public string GetSmartApiUrl(IPAddress remoteAddr)
  704. {
  705. // Published server ends with a /
  706. if (!string.IsNullOrEmpty(PublishedServerUrl))
  707. {
  708. // Published server ends with a '/', so we need to remove it.
  709. return PublishedServerUrl.Trim('/');
  710. }
  711. string smart = NetManager.GetBindAddress(remoteAddr, out var port);
  712. return GetLocalApiUrl(smart.Trim('/'), null, port);
  713. }
  714. /// <inheritdoc/>
  715. public string GetSmartApiUrl(HttpRequest request)
  716. {
  717. // Return the host in the HTTP request as the API URL if not configured otherwise
  718. if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
  719. {
  720. int? requestPort = request.Host.Port;
  721. if (requestPort is null
  722. || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
  723. || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
  724. {
  725. requestPort = -1;
  726. }
  727. return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
  728. }
  729. return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
  730. }
  731. /// <inheritdoc/>
  732. public string GetSmartApiUrl(string hostname)
  733. {
  734. // Published server ends with a /
  735. if (!string.IsNullOrEmpty(PublishedServerUrl))
  736. {
  737. // Published server ends with a '/', so we need to remove it.
  738. return PublishedServerUrl.Trim('/');
  739. }
  740. string smart = NetManager.GetBindAddress(hostname, out var port);
  741. return GetLocalApiUrl(smart.Trim('/'), null, port);
  742. }
  743. /// <inheritdoc/>
  744. public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
  745. {
  746. // With an empty source, the port will be null
  747. var smart = NetManager.GetBindAddress(ipAddress, out _, false);
  748. var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
  749. int? port = !allowHttps ? HttpPort : null;
  750. return GetLocalApiUrl(smart, scheme, port);
  751. }
  752. /// <inheritdoc/>
  753. public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
  754. {
  755. // If the smartAPI doesn't start with http then treat it as a host or ip.
  756. if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  757. {
  758. return hostname.TrimEnd('/');
  759. }
  760. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  761. // not. For consistency, always trim the trailing slash.
  762. scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
  763. var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
  764. return new UriBuilder
  765. {
  766. Scheme = scheme,
  767. Host = hostname,
  768. Port = port ?? (isHttps ? HttpsPort : HttpPort),
  769. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  770. }.ToString().TrimEnd('/');
  771. }
  772. public IEnumerable<Assembly> GetApiPluginAssemblies()
  773. {
  774. var assemblies = _allConcreteTypes
  775. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  776. .Select(i => i.Assembly)
  777. .Distinct();
  778. foreach (var assembly in assemblies)
  779. {
  780. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  781. yield return assembly;
  782. }
  783. }
  784. /// <inheritdoc />
  785. public void Dispose()
  786. {
  787. Dispose(true);
  788. GC.SuppressFinalize(this);
  789. }
  790. /// <summary>
  791. /// Releases unmanaged and - optionally - managed resources.
  792. /// </summary>
  793. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  794. protected virtual void Dispose(bool dispose)
  795. {
  796. if (_disposed)
  797. {
  798. return;
  799. }
  800. if (dispose)
  801. {
  802. var type = GetType();
  803. Logger.LogInformation("Disposing {Type}", type.Name);
  804. foreach (var part in _disposableParts.ToArray())
  805. {
  806. var partType = part.GetType();
  807. if (partType == type)
  808. {
  809. continue;
  810. }
  811. Logger.LogInformation("Disposing {Type}", partType.Name);
  812. try
  813. {
  814. part.Dispose();
  815. }
  816. catch (Exception ex)
  817. {
  818. Logger.LogError(ex, "Error disposing {Type}", partType.Name);
  819. }
  820. }
  821. _disposableParts.Clear();
  822. }
  823. _disposed = true;
  824. }
  825. }
  826. }