ApplicationHost.cs 45 KB

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