ApplicationHost.cs 38 KB

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