ApplicationHost.cs 45 KB

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