ApplicationHost.cs 42 KB

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