ApplicationHost.cs 45 KB

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