ApplicationHost.cs 45 KB

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