ApplicationHost.cs 45 KB

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