ApplicationHost.cs 38 KB

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