ApplicationHost.cs 38 KB

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