ApplicationHost.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  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(_fileSystemManager));
  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.HttpServerPortNumber;
  405. HttpsPort = networkConfiguration.HttpsPortNumber;
  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. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  508. await localizationManager.LoadAll().ConfigureAwait(false);
  509. _sessionManager = Resolve<ISessionManager>();
  510. SetStaticProperties();
  511. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  512. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  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.HttpServerPortNumber != HttpPort
  644. || networkConfiguration.HttpsPortNumber != 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.GetBindInterface(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 == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
  827. {
  828. requestPort = -1;
  829. }
  830. return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
  831. }
  832. return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
  833. }
  834. /// <inheritdoc/>
  835. public string GetSmartApiUrl(string hostname)
  836. {
  837. // Published server ends with a /
  838. if (!string.IsNullOrEmpty(PublishedServerUrl))
  839. {
  840. // Published server ends with a '/', so we need to remove it.
  841. return PublishedServerUrl.Trim('/');
  842. }
  843. string smart = NetManager.GetBindInterface(hostname, out var port);
  844. return GetLocalApiUrl(smart.Trim('/'), null, port);
  845. }
  846. /// <inheritdoc/>
  847. public string GetApiUrlForLocalAccess(IPObject hostname = null, bool allowHttps = true)
  848. {
  849. // With an empty source, the port will be null
  850. var smart = NetManager.GetBindInterface(hostname ?? IPHost.None, out _);
  851. var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
  852. int? port = !allowHttps ? HttpPort : null;
  853. return GetLocalApiUrl(smart, scheme, port);
  854. }
  855. /// <inheritdoc/>
  856. public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
  857. {
  858. // If the smartAPI doesn't start with http then treat it as a host or ip.
  859. if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  860. {
  861. return hostname.TrimEnd('/');
  862. }
  863. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  864. // not. For consistency, always trim the trailing slash.
  865. scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
  866. var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
  867. return new UriBuilder
  868. {
  869. Scheme = scheme,
  870. Host = hostname,
  871. Port = port ?? (isHttps ? HttpsPort : HttpPort),
  872. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  873. }.ToString().TrimEnd('/');
  874. }
  875. /// <inheritdoc />
  876. public async Task Shutdown()
  877. {
  878. if (IsShuttingDown)
  879. {
  880. return;
  881. }
  882. IsShuttingDown = true;
  883. try
  884. {
  885. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  886. }
  887. catch (Exception ex)
  888. {
  889. Logger.LogError(ex, "Error sending server shutdown notification");
  890. }
  891. ShutdownInternal();
  892. }
  893. protected abstract void ShutdownInternal();
  894. public IEnumerable<Assembly> GetApiPluginAssemblies()
  895. {
  896. var assemblies = _allConcreteTypes
  897. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  898. .Select(i => i.Assembly)
  899. .Distinct();
  900. foreach (var assembly in assemblies)
  901. {
  902. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  903. yield return assembly;
  904. }
  905. }
  906. /// <inheritdoc />
  907. public void Dispose()
  908. {
  909. Dispose(true);
  910. GC.SuppressFinalize(this);
  911. }
  912. /// <summary>
  913. /// Releases unmanaged and - optionally - managed resources.
  914. /// </summary>
  915. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  916. protected virtual void Dispose(bool dispose)
  917. {
  918. if (_disposed)
  919. {
  920. return;
  921. }
  922. if (dispose)
  923. {
  924. var type = GetType();
  925. Logger.LogInformation("Disposing {Type}", type.Name);
  926. foreach (var (part, _) in _disposableParts)
  927. {
  928. var partType = part.GetType();
  929. if (partType == type)
  930. {
  931. continue;
  932. }
  933. Logger.LogInformation("Disposing {Type}", partType.Name);
  934. try
  935. {
  936. part.Dispose();
  937. }
  938. catch (Exception ex)
  939. {
  940. Logger.LogError(ex, "Error disposing {Type}", partType.Name);
  941. }
  942. }
  943. _disposableParts.Clear();
  944. }
  945. _disposed = true;
  946. }
  947. public async ValueTask DisposeAsync()
  948. {
  949. await DisposeAsyncCore().ConfigureAwait(false);
  950. Dispose(false);
  951. GC.SuppressFinalize(this);
  952. }
  953. /// <summary>
  954. /// Used to perform asynchronous cleanup of managed resources or for cascading calls to <see cref="DisposeAsync"/>.
  955. /// </summary>
  956. /// <returns>A ValueTask.</returns>
  957. protected virtual async ValueTask DisposeAsyncCore()
  958. {
  959. var type = GetType();
  960. Logger.LogInformation("Disposing {Type}", type.Name);
  961. foreach (var (part, _) in _disposableParts)
  962. {
  963. var partType = part.GetType();
  964. if (partType == type)
  965. {
  966. continue;
  967. }
  968. Logger.LogInformation("Disposing {Type}", partType.Name);
  969. try
  970. {
  971. part.Dispose();
  972. }
  973. catch (Exception ex)
  974. {
  975. Logger.LogError(ex, "Error disposing {Type}", partType.Name);
  976. }
  977. }
  978. if (_sessionManager != null)
  979. {
  980. // used for closing websockets
  981. foreach (var session in _sessionManager.Sessions)
  982. {
  983. await session.DisposeAsync().ConfigureAwait(false);
  984. }
  985. }
  986. }
  987. }
  988. }