ApplicationHost.cs 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Reflection;
  10. using System.Runtime.InteropServices;
  11. using System.Security.Cryptography.X509Certificates;
  12. using System.Text;
  13. using System.Text.Json;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using Emby.Dlna;
  17. using Emby.Dlna.Main;
  18. using Emby.Dlna.Ssdp;
  19. using Emby.Drawing;
  20. using Emby.Notifications;
  21. using Emby.Photos;
  22. using Emby.Server.Implementations.Archiving;
  23. using Emby.Server.Implementations.Channels;
  24. using Emby.Server.Implementations.Collections;
  25. using Emby.Server.Implementations.Configuration;
  26. using Emby.Server.Implementations.Cryptography;
  27. using Emby.Server.Implementations.Data;
  28. using Emby.Server.Implementations.Devices;
  29. using Emby.Server.Implementations.Dto;
  30. using Emby.Server.Implementations.HttpServer.Security;
  31. using Emby.Server.Implementations.IO;
  32. using Emby.Server.Implementations.Library;
  33. using Emby.Server.Implementations.LiveTv;
  34. using Emby.Server.Implementations.Localization;
  35. using Emby.Server.Implementations.Net;
  36. using Emby.Server.Implementations.Playlists;
  37. using Emby.Server.Implementations.Plugins;
  38. using Emby.Server.Implementations.QuickConnect;
  39. using Emby.Server.Implementations.ScheduledTasks;
  40. using Emby.Server.Implementations.Security;
  41. using Emby.Server.Implementations.Serialization;
  42. using Emby.Server.Implementations.Session;
  43. using Emby.Server.Implementations.SyncPlay;
  44. using Emby.Server.Implementations.TV;
  45. using Emby.Server.Implementations.Updates;
  46. using Jellyfin.Api.Helpers;
  47. using Jellyfin.Networking.Configuration;
  48. using Jellyfin.Networking.Manager;
  49. using MediaBrowser.Common;
  50. using MediaBrowser.Common.Configuration;
  51. using MediaBrowser.Common.Events;
  52. using MediaBrowser.Common.Json;
  53. using MediaBrowser.Common.Net;
  54. using MediaBrowser.Common.Plugins;
  55. using MediaBrowser.Common.Updates;
  56. using MediaBrowser.Controller;
  57. using MediaBrowser.Controller.Channels;
  58. using MediaBrowser.Controller.Chapters;
  59. using MediaBrowser.Controller.Collections;
  60. using MediaBrowser.Controller.Configuration;
  61. using MediaBrowser.Controller.Devices;
  62. using MediaBrowser.Controller.Dlna;
  63. using MediaBrowser.Controller.Drawing;
  64. using MediaBrowser.Controller.Dto;
  65. using MediaBrowser.Controller.Entities;
  66. using MediaBrowser.Controller.Library;
  67. using MediaBrowser.Controller.LiveTv;
  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.Security;
  78. using MediaBrowser.Controller.Session;
  79. using MediaBrowser.Controller.Sorting;
  80. using MediaBrowser.Controller.Subtitles;
  81. using MediaBrowser.Controller.SyncPlay;
  82. using MediaBrowser.Controller.TV;
  83. using MediaBrowser.LocalMetadata.Savers;
  84. using MediaBrowser.MediaEncoding.BdInfo;
  85. using MediaBrowser.Model.Cryptography;
  86. using MediaBrowser.Model.Dlna;
  87. using MediaBrowser.Model.Globalization;
  88. using MediaBrowser.Model.IO;
  89. using MediaBrowser.Model.MediaInfo;
  90. using MediaBrowser.Model.Net;
  91. using MediaBrowser.Model.Serialization;
  92. using MediaBrowser.Model.System;
  93. using MediaBrowser.Model.Tasks;
  94. using MediaBrowser.Providers.Chapters;
  95. using MediaBrowser.Providers.Manager;
  96. using MediaBrowser.Providers.Plugins.Tmdb;
  97. using MediaBrowser.Providers.Subtitles;
  98. using MediaBrowser.XbmcMetadata.Providers;
  99. using Microsoft.AspNetCore.Http;
  100. using Microsoft.AspNetCore.Mvc;
  101. using Microsoft.Extensions.DependencyInjection;
  102. using Microsoft.Extensions.Logging;
  103. using Prometheus.DotNetRuntime;
  104. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  105. using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
  106. namespace Emby.Server.Implementations
  107. {
  108. /// <summary>
  109. /// Class CompositionRoot.
  110. /// </summary>
  111. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  112. {
  113. /// <summary>
  114. /// The environment variable prefixes to log at server startup.
  115. /// </summary>
  116. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  117. private readonly IFileSystem _fileSystemManager;
  118. private readonly IXmlSerializer _xmlSerializer;
  119. private readonly IStartupOptions _startupOptions;
  120. private IMediaEncoder _mediaEncoder;
  121. private ISessionManager _sessionManager;
  122. private string[] _urlPrefixes;
  123. private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions();
  124. /// <summary>
  125. /// Gets a value indicating whether this instance can self restart.
  126. /// </summary>
  127. public bool CanSelfRestart => _startupOptions.RestartPath != null;
  128. public bool CoreStartupHasCompleted { get; private set; }
  129. public virtual bool CanLaunchWebBrowser
  130. {
  131. get
  132. {
  133. if (!Environment.UserInteractive)
  134. {
  135. return false;
  136. }
  137. if (_startupOptions.IsService)
  138. {
  139. return false;
  140. }
  141. if (OperatingSystem.Id == OperatingSystemId.Windows
  142. || OperatingSystem.Id == OperatingSystemId.Darwin)
  143. {
  144. return true;
  145. }
  146. return false;
  147. }
  148. }
  149. /// <summary>
  150. /// Gets the <see cref="INetworkManager"/> singleton instance.
  151. /// </summary>
  152. public INetworkManager NetManager { get; internal set; }
  153. /// <summary>
  154. /// Occurs when [has pending restart changed].
  155. /// </summary>
  156. public event EventHandler HasPendingRestartChanged;
  157. /// <summary>
  158. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  159. /// </summary>
  160. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  161. public bool HasPendingRestart { get; private set; }
  162. /// <inheritdoc />
  163. public bool IsShuttingDown { get; private set; }
  164. /// <summary>
  165. /// Gets the logger.
  166. /// </summary>
  167. protected ILogger<ApplicationHost> Logger { get; }
  168. protected IServiceCollection ServiceCollection { get; }
  169. private IPlugin[] _plugins;
  170. private IReadOnlyList<LocalPlugin> _pluginsManifests;
  171. /// <summary>
  172. /// Gets the plugins.
  173. /// </summary>
  174. /// <value>The plugins.</value>
  175. public IReadOnlyList<IPlugin> Plugins => _plugins;
  176. /// <summary>
  177. /// Gets the logger factory.
  178. /// </summary>
  179. protected ILoggerFactory LoggerFactory { get; }
  180. /// <summary>
  181. /// Gets or sets the application paths.
  182. /// </summary>
  183. /// <value>The application paths.</value>
  184. protected IServerApplicationPaths ApplicationPaths { get; set; }
  185. /// <summary>
  186. /// Gets or sets all concrete types.
  187. /// </summary>
  188. /// <value>All concrete types.</value>
  189. private Type[] _allConcreteTypes;
  190. /// <summary>
  191. /// The disposable parts.
  192. /// </summary>
  193. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  194. /// <summary>
  195. /// Gets or sets the configuration manager.
  196. /// </summary>
  197. /// <value>The configuration manager.</value>
  198. protected IConfigurationManager ConfigurationManager { get; set; }
  199. /// <summary>
  200. /// Gets or sets the service provider.
  201. /// </summary>
  202. public IServiceProvider ServiceProvider { get; set; }
  203. /// <summary>
  204. /// Gets the http port for the webhost.
  205. /// </summary>
  206. public int HttpPort { get; private set; }
  207. /// <summary>
  208. /// Gets the https port for the webhost.
  209. /// </summary>
  210. public int HttpsPort { get; private set; }
  211. /// <summary>
  212. /// Gets the server configuration manager.
  213. /// </summary>
  214. /// <value>The server configuration manager.</value>
  215. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  216. /// <summary>
  217. /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
  218. /// </summary>
  219. /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
  220. /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
  221. /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
  222. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  223. /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
  224. public ApplicationHost(
  225. IServerApplicationPaths applicationPaths,
  226. ILoggerFactory loggerFactory,
  227. IStartupOptions options,
  228. IFileSystem fileSystem,
  229. IServiceCollection serviceCollection)
  230. {
  231. _xmlSerializer = new MyXmlSerializer();
  232. ServiceCollection = serviceCollection;
  233. ApplicationPaths = applicationPaths;
  234. LoggerFactory = loggerFactory;
  235. _fileSystemManager = fileSystem;
  236. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
  237. // Have to migrate settings here as migration subsystem not yet initialised.
  238. MigrateNetworkConfiguration();
  239. // Have to pre-register the NetworkConfigurationFactory, as the configuration sub-system is not yet initialised.
  240. ConfigurationManager.RegisterConfiguration<NetworkConfigurationFactory>();
  241. NetManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger<NetworkManager>());
  242. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  243. _startupOptions = options;
  244. // Initialize runtime stat collection
  245. if (ServerConfigurationManager.Configuration.EnableMetrics)
  246. {
  247. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  248. }
  249. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  250. ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
  251. ApplicationVersionString = ApplicationVersion.ToString(3);
  252. ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  253. }
  254. /// <summary>
  255. /// Temporary function to migration network settings out of system.xml and into network.xml.
  256. /// TODO: remove at the point when a fixed migration path has been decided upon.
  257. /// </summary>
  258. private void MigrateNetworkConfiguration()
  259. {
  260. string path = Path.Combine(ConfigurationManager.CommonApplicationPaths.ConfigurationDirectoryPath, "network.xml");
  261. if (!File.Exists(path))
  262. {
  263. var networkSettings = new NetworkConfiguration();
  264. ClassMigrationHelper.CopyProperties(ServerConfigurationManager.Configuration, networkSettings);
  265. _xmlSerializer.SerializeToFile(networkSettings, path);
  266. Logger?.LogDebug("Successfully migrated network settings.");
  267. }
  268. }
  269. public string ExpandVirtualPath(string path)
  270. {
  271. var appPaths = ApplicationPaths;
  272. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  273. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  274. }
  275. public string ReverseVirtualPath(string path)
  276. {
  277. var appPaths = ApplicationPaths;
  278. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  279. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  280. }
  281. /// <inheritdoc />
  282. public Version ApplicationVersion { get; }
  283. /// <inheritdoc />
  284. public string ApplicationVersionString { get; }
  285. /// <summary>
  286. /// Gets the current application user agent.
  287. /// </summary>
  288. /// <value>The application user agent.</value>
  289. public string ApplicationUserAgent { get; }
  290. /// <summary>
  291. /// Gets the email address for use within a comment section of a user agent field.
  292. /// Presently used to provide contact information to MusicBrainz service.
  293. /// </summary>
  294. public string ApplicationUserAgentAddress => "team@jellyfin.org";
  295. /// <summary>
  296. /// Gets the current application name.
  297. /// </summary>
  298. /// <value>The application name.</value>
  299. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  300. private DeviceId _deviceId;
  301. public string SystemId
  302. {
  303. get
  304. {
  305. if (_deviceId == null)
  306. {
  307. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  308. }
  309. return _deviceId.Value;
  310. }
  311. }
  312. /// <inheritdoc/>
  313. public string Name => ApplicationProductName;
  314. /// <summary>
  315. /// Creates an instance of type and resolves all constructor dependencies.
  316. /// </summary>
  317. /// <param name="type">The type.</param>
  318. /// <returns>System.Object.</returns>
  319. public object CreateInstance(Type type)
  320. => ActivatorUtilities.CreateInstance(ServiceProvider, type);
  321. /// <summary>
  322. /// Creates an instance of type and resolves all constructor dependencies.
  323. /// </summary>
  324. /// /// <typeparam name="T">The type.</typeparam>
  325. /// <returns>T.</returns>
  326. public T CreateInstance<T>()
  327. => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
  328. /// <summary>
  329. /// Creates the instance safe.
  330. /// </summary>
  331. /// <param name="type">The type.</param>
  332. /// <returns>System.Object.</returns>
  333. protected object CreateInstanceSafe(Type type)
  334. {
  335. try
  336. {
  337. Logger.LogDebug("Creating instance of {Type}", type);
  338. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  339. }
  340. catch (Exception ex)
  341. {
  342. Logger.LogError(ex, "Error creating {Type}", type);
  343. return null;
  344. }
  345. }
  346. /// <summary>
  347. /// Resolves this instance.
  348. /// </summary>
  349. /// <typeparam name="T">The type.</typeparam>
  350. /// <returns>``0.</returns>
  351. public T Resolve<T>() => ServiceProvider.GetService<T>();
  352. /// <summary>
  353. /// Gets the export types.
  354. /// </summary>
  355. /// <typeparam name="T">The type.</typeparam>
  356. /// <returns>IEnumerable{Type}.</returns>
  357. public IEnumerable<Type> GetExportTypes<T>()
  358. {
  359. var currentType = typeof(T);
  360. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  361. }
  362. /// <inheritdoc />
  363. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  364. {
  365. // Convert to list so this isn't executed for each iteration
  366. var parts = GetExportTypes<T>()
  367. .Select(CreateInstanceSafe)
  368. .Where(i => i != null)
  369. .Cast<T>()
  370. .ToList();
  371. if (manageLifetime)
  372. {
  373. lock (_disposableParts)
  374. {
  375. _disposableParts.AddRange(parts.OfType<IDisposable>());
  376. }
  377. }
  378. return parts;
  379. }
  380. /// <summary>
  381. /// Runs the startup tasks.
  382. /// </summary>
  383. /// <returns><see cref="Task" />.</returns>
  384. public async Task RunStartupTasksAsync()
  385. {
  386. Logger.LogInformation("Running startup tasks");
  387. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  388. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  389. ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
  390. _mediaEncoder.SetFFmpegPath();
  391. Logger.LogInformation("ServerId: {0}", SystemId);
  392. var entryPoints = GetExports<IServerEntryPoint>();
  393. var stopWatch = new Stopwatch();
  394. stopWatch.Start();
  395. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  396. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  397. Logger.LogInformation("Core startup complete");
  398. CoreStartupHasCompleted = true;
  399. stopWatch.Restart();
  400. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  401. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  402. stopWatch.Stop();
  403. }
  404. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  405. {
  406. foreach (var entryPoint in entryPoints)
  407. {
  408. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  409. {
  410. continue;
  411. }
  412. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  413. yield return entryPoint.RunAsync();
  414. }
  415. }
  416. /// <inheritdoc/>
  417. public void Init()
  418. {
  419. var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration();
  420. HttpPort = networkConfiguration.HttpServerPortNumber;
  421. HttpsPort = networkConfiguration.HttpsPortNumber;
  422. // Safeguard against invalid configuration
  423. if (HttpPort == HttpsPort)
  424. {
  425. HttpPort = NetworkConfiguration.DefaultHttpPort;
  426. HttpsPort = NetworkConfiguration.DefaultHttpsPort;
  427. }
  428. CertificateInfo = new CertificateInfo
  429. {
  430. Path = networkConfiguration.CertificatePath,
  431. Password = networkConfiguration.CertificatePassword
  432. };
  433. Certificate = GetCertificate(CertificateInfo);
  434. DiscoverTypes();
  435. RegisterServices();
  436. RegisterPluginServices();
  437. }
  438. /// <summary>
  439. /// Registers services/resources with the service collection that will be available via DI.
  440. /// </summary>
  441. protected virtual void RegisterServices()
  442. {
  443. ServiceCollection.AddSingleton(_startupOptions);
  444. ServiceCollection.AddMemoryCache();
  445. ServiceCollection.AddSingleton(ConfigurationManager);
  446. ServiceCollection.AddSingleton<IApplicationHost>(this);
  447. ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  448. ServiceCollection.AddSingleton(_fileSystemManager);
  449. ServiceCollection.AddSingleton<TmdbClientManager>();
  450. ServiceCollection.AddSingleton(NetManager);
  451. ServiceCollection.AddSingleton<ITaskManager, TaskManager>();
  452. ServiceCollection.AddSingleton(_xmlSerializer);
  453. ServiceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  454. ServiceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  455. ServiceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  456. ServiceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  457. ServiceCollection.AddSingleton<IZipClient, ZipClient>();
  458. ServiceCollection.AddSingleton<IServerApplicationHost>(this);
  459. ServiceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  460. ServiceCollection.AddSingleton(ServerConfigurationManager);
  461. ServiceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  462. ServiceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  463. ServiceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  464. ServiceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  465. ServiceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  466. ServiceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  467. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  468. ServiceCollection.AddTransient(provider => new Lazy<IDtoService>(provider.GetRequiredService<IDtoService>));
  469. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  470. ServiceCollection.AddTransient(provider => new Lazy<EncodingHelper>(provider.GetRequiredService<EncodingHelper>));
  471. ServiceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  472. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  473. ServiceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  474. ServiceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  475. ServiceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  476. ServiceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  477. ServiceCollection.AddSingleton<IMusicManager, MusicManager>();
  478. ServiceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  479. ServiceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  480. ServiceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  481. ServiceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  482. ServiceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  483. ServiceCollection.AddSingleton<IDeviceManager, DeviceManager>();
  484. ServiceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  485. ServiceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  486. ServiceCollection.AddSingleton<IProviderManager, ProviderManager>();
  487. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  488. ServiceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  489. ServiceCollection.AddSingleton<IDtoService, DtoService>();
  490. ServiceCollection.AddSingleton<IChannelManager, ChannelManager>();
  491. ServiceCollection.AddSingleton<ISessionManager, SessionManager>();
  492. ServiceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  493. ServiceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  494. ServiceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  495. ServiceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  496. ServiceCollection.AddSingleton<LiveTvDtoService>();
  497. ServiceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  498. ServiceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  499. ServiceCollection.AddSingleton<INotificationManager, NotificationManager>();
  500. ServiceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  501. ServiceCollection.AddSingleton<IChapterManager, ChapterManager>();
  502. ServiceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  503. ServiceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  504. ServiceCollection.AddSingleton<ISessionContext, SessionContext>();
  505. ServiceCollection.AddSingleton<IAuthService, AuthService>();
  506. ServiceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  507. ServiceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  508. ServiceCollection.AddSingleton<EncodingHelper>();
  509. ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  510. ServiceCollection.AddSingleton<TranscodingJobHelper>();
  511. ServiceCollection.AddScoped<MediaInfoHelper>();
  512. ServiceCollection.AddScoped<AudioHelper>();
  513. ServiceCollection.AddScoped<DynamicHlsHelper>();
  514. }
  515. /// <summary>
  516. /// Create services registered with the service container that need to be initialized at application startup.
  517. /// </summary>
  518. /// <returns>A task representing the service initialization operation.</returns>
  519. public async Task InitializeServices()
  520. {
  521. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  522. await localizationManager.LoadAll().ConfigureAwait(false);
  523. _mediaEncoder = Resolve<IMediaEncoder>();
  524. _sessionManager = Resolve<ISessionManager>();
  525. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  526. SetStaticProperties();
  527. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  528. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  529. FindParts();
  530. }
  531. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  532. {
  533. // Distinct these to prevent users from reporting problems that aren't actually problems
  534. var commandLineArgs = Environment
  535. .GetCommandLineArgs()
  536. .Distinct();
  537. // Get all relevant environment variables
  538. var allEnvVars = Environment.GetEnvironmentVariables();
  539. var relevantEnvVars = new Dictionary<object, object>();
  540. foreach (var key in allEnvVars.Keys)
  541. {
  542. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  543. {
  544. relevantEnvVars.Add(key, allEnvVars[key]);
  545. }
  546. }
  547. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  548. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  549. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  550. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  551. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  552. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  553. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  554. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  555. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  556. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  557. }
  558. private X509Certificate2 GetCertificate(CertificateInfo info)
  559. {
  560. var certificateLocation = info?.Path;
  561. if (string.IsNullOrWhiteSpace(certificateLocation))
  562. {
  563. return null;
  564. }
  565. try
  566. {
  567. if (!File.Exists(certificateLocation))
  568. {
  569. return null;
  570. }
  571. // Don't use an empty string password
  572. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  573. var localCert = new X509Certificate2(certificateLocation, password, X509KeyStorageFlags.UserKeySet);
  574. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  575. if (!localCert.HasPrivateKey)
  576. {
  577. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  578. return null;
  579. }
  580. return localCert;
  581. }
  582. catch (Exception ex)
  583. {
  584. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  585. return null;
  586. }
  587. }
  588. /// <summary>
  589. /// Dirty hacks.
  590. /// </summary>
  591. private void SetStaticProperties()
  592. {
  593. // For now there's no real way to inject these properly
  594. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  595. BaseItem.ConfigurationManager = ServerConfigurationManager;
  596. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  597. BaseItem.ProviderManager = Resolve<IProviderManager>();
  598. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  599. BaseItem.ItemRepository = Resolve<IItemRepository>();
  600. BaseItem.FileSystem = _fileSystemManager;
  601. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  602. BaseItem.ChannelManager = Resolve<IChannelManager>();
  603. Video.LiveTvManager = Resolve<ILiveTvManager>();
  604. Folder.UserViewManager = Resolve<IUserViewManager>();
  605. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  606. UserView.CollectionManager = Resolve<ICollectionManager>();
  607. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  608. CollectionFolder.XmlSerializer = _xmlSerializer;
  609. CollectionFolder.ApplicationHost = this;
  610. }
  611. /// <summary>
  612. /// Finds plugin components and register them with the appropriate services.
  613. /// </summary>
  614. private void FindParts()
  615. {
  616. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  617. {
  618. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  619. ConfigurationManager.SaveConfiguration();
  620. }
  621. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  622. _plugins = GetExports<IPlugin>()
  623. .Where(i => i != null)
  624. .ToArray();
  625. if (Plugins != null)
  626. {
  627. foreach (var plugin in Plugins)
  628. {
  629. if (_pluginsManifests != null && plugin is IPluginAssembly assemblyPlugin)
  630. {
  631. // Ensure the version number matches the Plugin Manifest information.
  632. foreach (var item in _pluginsManifests)
  633. {
  634. if (Path.GetDirectoryName(plugin.AssemblyFilePath).Equals(item.Path, StringComparison.OrdinalIgnoreCase))
  635. {
  636. // Update version number to that of the manifest.
  637. assemblyPlugin.SetAttributes(
  638. plugin.AssemblyFilePath,
  639. Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(plugin.AssemblyFilePath)),
  640. item.Version);
  641. break;
  642. }
  643. }
  644. }
  645. Logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version);
  646. }
  647. }
  648. _urlPrefixes = GetUrlPrefixes().ToArray();
  649. Resolve<ILibraryManager>().AddParts(
  650. GetExports<IResolverIgnoreRule>(),
  651. GetExports<IItemResolver>(),
  652. GetExports<IIntroProvider>(),
  653. GetExports<IBaseItemComparer>(),
  654. GetExports<ILibraryPostScanTask>());
  655. Resolve<IProviderManager>().AddParts(
  656. GetExports<IImageProvider>(),
  657. GetExports<IMetadataService>(),
  658. GetExports<IMetadataProvider>(),
  659. GetExports<IMetadataSaver>(),
  660. GetExports<IExternalId>());
  661. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  662. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  663. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  664. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  665. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  666. }
  667. /// <summary>
  668. /// Discovers the types.
  669. /// </summary>
  670. protected void DiscoverTypes()
  671. {
  672. Logger.LogInformation("Loading assemblies");
  673. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  674. }
  675. private void RegisterPluginServices()
  676. {
  677. foreach (var pluginServiceRegistrator in GetExportTypes<IPluginServiceRegistrator>())
  678. {
  679. try
  680. {
  681. var instance = (IPluginServiceRegistrator)Activator.CreateInstance(pluginServiceRegistrator);
  682. instance.RegisterServices(ServiceCollection);
  683. }
  684. catch (Exception ex)
  685. {
  686. Logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly);
  687. }
  688. }
  689. }
  690. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  691. {
  692. foreach (var ass in assemblies)
  693. {
  694. Type[] exportedTypes;
  695. try
  696. {
  697. exportedTypes = ass.GetExportedTypes();
  698. }
  699. catch (FileNotFoundException ex)
  700. {
  701. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  702. continue;
  703. }
  704. catch (TypeLoadException ex)
  705. {
  706. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  707. continue;
  708. }
  709. foreach (Type type in exportedTypes)
  710. {
  711. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  712. {
  713. yield return type;
  714. }
  715. }
  716. }
  717. }
  718. private CertificateInfo CertificateInfo { get; set; }
  719. public X509Certificate2 Certificate { get; private set; }
  720. private IEnumerable<string> GetUrlPrefixes()
  721. {
  722. var hosts = new[] { "+" };
  723. return hosts.SelectMany(i =>
  724. {
  725. var prefixes = new List<string>
  726. {
  727. "http://" + i + ":" + HttpPort + "/"
  728. };
  729. if (CertificateInfo != null)
  730. {
  731. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  732. }
  733. return prefixes;
  734. });
  735. }
  736. /// <summary>
  737. /// Called when [configuration updated].
  738. /// </summary>
  739. /// <param name="sender">The sender.</param>
  740. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  741. protected void OnConfigurationUpdated(object sender, EventArgs e)
  742. {
  743. var requiresRestart = false;
  744. var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration();
  745. // Don't do anything if these haven't been set yet
  746. if (HttpPort != 0 && HttpsPort != 0)
  747. {
  748. // Need to restart if ports have changed
  749. if (networkConfiguration.HttpServerPortNumber != HttpPort ||
  750. networkConfiguration.HttpsPortNumber != HttpsPort)
  751. {
  752. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  753. {
  754. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  755. ServerConfigurationManager.SaveConfiguration();
  756. requiresRestart = true;
  757. }
  758. }
  759. }
  760. if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  761. {
  762. requiresRestart = true;
  763. }
  764. if (ValidateSslCertificate(networkConfiguration))
  765. {
  766. requiresRestart = true;
  767. }
  768. if (requiresRestart)
  769. {
  770. Logger.LogInformation("App needs to be restarted due to configuration change.");
  771. NotifyPendingRestart();
  772. }
  773. }
  774. /// <summary>
  775. /// Validates the SSL certificate.
  776. /// </summary>
  777. /// <param name="networkConfig">The new configuration.</param>
  778. /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
  779. private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
  780. {
  781. var newPath = networkConfig.CertificatePath;
  782. if (!string.IsNullOrWhiteSpace(newPath)
  783. && !string.Equals(CertificateInfo?.Path, newPath, StringComparison.Ordinal))
  784. {
  785. if (File.Exists(newPath))
  786. {
  787. return true;
  788. }
  789. throw new FileNotFoundException(
  790. string.Format(
  791. CultureInfo.InvariantCulture,
  792. "Certificate file '{0}' does not exist.",
  793. newPath));
  794. }
  795. return false;
  796. }
  797. /// <summary>
  798. /// Notifies that the kernel that a change has been made that requires a restart.
  799. /// </summary>
  800. public void NotifyPendingRestart()
  801. {
  802. Logger.LogInformation("App needs to be restarted.");
  803. var changed = !HasPendingRestart;
  804. HasPendingRestart = true;
  805. if (changed)
  806. {
  807. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  808. }
  809. }
  810. /// <summary>
  811. /// Restarts this instance.
  812. /// </summary>
  813. public void Restart()
  814. {
  815. if (!CanSelfRestart)
  816. {
  817. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  818. }
  819. if (IsShuttingDown)
  820. {
  821. return;
  822. }
  823. IsShuttingDown = true;
  824. Task.Run(async () =>
  825. {
  826. try
  827. {
  828. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  829. }
  830. catch (Exception ex)
  831. {
  832. Logger.LogError(ex, "Error sending server restart notification");
  833. }
  834. Logger.LogInformation("Calling RestartInternal");
  835. RestartInternal();
  836. });
  837. }
  838. protected abstract void RestartInternal();
  839. /// <inheritdoc/>
  840. public IEnumerable<LocalPlugin> GetLocalPlugins(string path, bool cleanup = true)
  841. {
  842. var minimumVersion = new Version(0, 0, 0, 1);
  843. var versions = new List<LocalPlugin>();
  844. if (!Directory.Exists(path))
  845. {
  846. // Plugin path doesn't exist, don't try to enumerate subfolders.
  847. return Enumerable.Empty<LocalPlugin>();
  848. }
  849. var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly);
  850. foreach (var dir in directories)
  851. {
  852. try
  853. {
  854. var metafile = Path.Combine(dir, "meta.json");
  855. if (File.Exists(metafile))
  856. {
  857. var jsonString = File.ReadAllText(metafile, Encoding.UTF8);
  858. var manifest = JsonSerializer.Deserialize<PluginManifest>(jsonString, _jsonOptions);
  859. if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
  860. {
  861. targetAbi = minimumVersion;
  862. }
  863. if (!Version.TryParse(manifest.Version, out var version))
  864. {
  865. version = minimumVersion;
  866. }
  867. if (ApplicationVersion >= targetAbi)
  868. {
  869. // Only load Plugins if the plugin is built for this version or below.
  870. versions.Add(new LocalPlugin(manifest.Guid, manifest.Name, version, dir));
  871. }
  872. }
  873. else
  874. {
  875. // No metafile, so lets see if the folder is versioned.
  876. metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
  877. int versionIndex = dir.LastIndexOf('_');
  878. if (versionIndex != -1 && Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version parsedVersion))
  879. {
  880. // Versioned folder.
  881. versions.Add(new LocalPlugin(Guid.Empty, metafile, parsedVersion, dir));
  882. }
  883. else
  884. {
  885. // Un-versioned folder - Add it under the path name and version 0.0.0.1.
  886. versions.Add(new LocalPlugin(Guid.Empty, metafile, minimumVersion, dir));
  887. }
  888. }
  889. }
  890. catch
  891. {
  892. continue;
  893. }
  894. }
  895. string lastName = string.Empty;
  896. versions.Sort(LocalPlugin.Compare);
  897. // Traverse backwards through the list.
  898. // The first item will be the latest version.
  899. for (int x = versions.Count - 1; x >= 0; x--)
  900. {
  901. if (!string.Equals(lastName, versions[x].Name, StringComparison.OrdinalIgnoreCase))
  902. {
  903. versions[x].DllFiles.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories));
  904. lastName = versions[x].Name;
  905. continue;
  906. }
  907. if (!string.IsNullOrEmpty(lastName) && cleanup)
  908. {
  909. // Attempt a cleanup of old folders.
  910. try
  911. {
  912. Logger.LogDebug("Deleting {Path}", versions[x].Path);
  913. Directory.Delete(versions[x].Path, true);
  914. }
  915. catch (Exception e)
  916. {
  917. Logger.LogWarning(e, "Unable to delete {Path}", versions[x].Path);
  918. }
  919. versions.RemoveAt(x);
  920. }
  921. }
  922. return versions;
  923. }
  924. /// <summary>
  925. /// Gets the composable part assemblies.
  926. /// </summary>
  927. /// <returns>IEnumerable{Assembly}.</returns>
  928. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  929. {
  930. if (Directory.Exists(ApplicationPaths.PluginsPath))
  931. {
  932. _pluginsManifests = GetLocalPlugins(ApplicationPaths.PluginsPath).ToList();
  933. foreach (var plugin in _pluginsManifests)
  934. {
  935. foreach (var file in plugin.DllFiles)
  936. {
  937. Assembly plugAss;
  938. try
  939. {
  940. plugAss = Assembly.LoadFrom(file);
  941. }
  942. catch (FileLoadException ex)
  943. {
  944. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  945. continue;
  946. }
  947. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  948. yield return plugAss;
  949. }
  950. }
  951. }
  952. // Include composable parts in the Model assembly
  953. yield return typeof(SystemInfo).Assembly;
  954. // Include composable parts in the Common assembly
  955. yield return typeof(IApplicationHost).Assembly;
  956. // Include composable parts in the Controller assembly
  957. yield return typeof(IServerApplicationHost).Assembly;
  958. // Include composable parts in the Providers assembly
  959. yield return typeof(ProviderUtils).Assembly;
  960. // Include composable parts in the Photos assembly
  961. yield return typeof(PhotoProvider).Assembly;
  962. // Emby.Server implementations
  963. yield return typeof(InstallationManager).Assembly;
  964. // MediaEncoding
  965. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  966. // Dlna
  967. yield return typeof(DlnaEntryPoint).Assembly;
  968. // Local metadata
  969. yield return typeof(BoxSetXmlSaver).Assembly;
  970. // Notifications
  971. yield return typeof(NotificationManager).Assembly;
  972. // Xbmc
  973. yield return typeof(ArtistNfoProvider).Assembly;
  974. // Network
  975. yield return typeof(NetworkManager).Assembly;
  976. foreach (var i in GetAssembliesWithPartsInternal())
  977. {
  978. yield return i;
  979. }
  980. }
  981. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  982. /// <summary>
  983. /// Gets the system status.
  984. /// </summary>
  985. /// <param name="source">Where this request originated.</param>
  986. /// <returns>SystemInfo.</returns>
  987. public SystemInfo GetSystemInfo(IPAddress source)
  988. {
  989. return new SystemInfo
  990. {
  991. HasPendingRestart = HasPendingRestart,
  992. IsShuttingDown = IsShuttingDown,
  993. Version = ApplicationVersionString,
  994. WebSocketPortNumber = HttpPort,
  995. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  996. Id = SystemId,
  997. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  998. WebPath = ApplicationPaths.WebPath,
  999. LogPath = ApplicationPaths.LogDirectoryPath,
  1000. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1001. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1002. CachePath = ApplicationPaths.CachePath,
  1003. OperatingSystem = OperatingSystem.Id.ToString(),
  1004. OperatingSystemDisplayName = OperatingSystem.Name,
  1005. CanSelfRestart = CanSelfRestart,
  1006. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1007. HasUpdateAvailable = HasUpdateAvailable,
  1008. TranscodingTempPath = ConfigurationManager.GetTranscodePath(),
  1009. ServerName = FriendlyName,
  1010. LocalAddress = GetSmartApiUrl(source),
  1011. SupportsLibraryMonitor = true,
  1012. EncoderLocation = _mediaEncoder.EncoderLocation,
  1013. SystemArchitecture = RuntimeInformation.OSArchitecture,
  1014. PackageName = _startupOptions.PackageName
  1015. };
  1016. }
  1017. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  1018. => NetManager.GetMacAddresses()
  1019. .Select(i => new WakeOnLanInfo(i))
  1020. .ToList();
  1021. public PublicSystemInfo GetPublicSystemInfo(IPAddress source)
  1022. {
  1023. return new PublicSystemInfo
  1024. {
  1025. Version = ApplicationVersionString,
  1026. ProductName = ApplicationProductName,
  1027. Id = SystemId,
  1028. OperatingSystem = OperatingSystem.Id.ToString(),
  1029. ServerName = FriendlyName,
  1030. LocalAddress = GetSmartApiUrl(source),
  1031. StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
  1032. };
  1033. }
  1034. /// <inheritdoc/>
  1035. public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.GetNetworkConfiguration().EnableHttps;
  1036. /// <inheritdoc/>
  1037. public string GetSmartApiUrl(IPAddress ipAddress, int? port = null)
  1038. {
  1039. // Published server ends with a /
  1040. if (_startupOptions.PublishedServerUrl != null)
  1041. {
  1042. // Published server ends with a '/', so we need to remove it.
  1043. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1044. }
  1045. string smart = NetManager.GetBindInterface(ipAddress, out port);
  1046. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1047. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1048. {
  1049. return smart.Trim('/');
  1050. }
  1051. return GetLocalApiUrl(smart.Trim('/'), null, port);
  1052. }
  1053. /// <inheritdoc/>
  1054. public string GetSmartApiUrl(HttpRequest request, int? port = null)
  1055. {
  1056. // Published server ends with a /
  1057. if (_startupOptions.PublishedServerUrl != null)
  1058. {
  1059. // Published server ends with a '/', so we need to remove it.
  1060. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1061. }
  1062. string smart = NetManager.GetBindInterface(request, out port);
  1063. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1064. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1065. {
  1066. return smart.Trim('/');
  1067. }
  1068. return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port);
  1069. }
  1070. /// <inheritdoc/>
  1071. public string GetSmartApiUrl(string hostname, int? port = null)
  1072. {
  1073. // Published server ends with a /
  1074. if (_startupOptions.PublishedServerUrl != null)
  1075. {
  1076. // Published server ends with a '/', so we need to remove it.
  1077. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1078. }
  1079. string smart = NetManager.GetBindInterface(hostname, out port);
  1080. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1081. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1082. {
  1083. return smart.Trim('/');
  1084. }
  1085. return GetLocalApiUrl(smart.Trim('/'), null, port);
  1086. }
  1087. /// <inheritdoc/>
  1088. public string GetLoopbackHttpApiUrl()
  1089. {
  1090. if (NetManager.IsIP6Enabled)
  1091. {
  1092. return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort);
  1093. }
  1094. return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
  1095. }
  1096. /// <inheritdoc/>
  1097. public string GetLocalApiUrl(string host, string scheme = null, int? port = null)
  1098. {
  1099. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  1100. // not. For consistency, always trim the trailing slash.
  1101. return new UriBuilder
  1102. {
  1103. Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
  1104. Host = host,
  1105. Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
  1106. Path = ServerConfigurationManager.GetNetworkConfiguration().BaseUrl
  1107. }.ToString().TrimEnd('/');
  1108. }
  1109. public string FriendlyName =>
  1110. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1111. ? Environment.MachineName
  1112. : ServerConfigurationManager.Configuration.ServerName;
  1113. /// <summary>
  1114. /// Shuts down.
  1115. /// </summary>
  1116. public async Task Shutdown()
  1117. {
  1118. if (IsShuttingDown)
  1119. {
  1120. return;
  1121. }
  1122. IsShuttingDown = true;
  1123. try
  1124. {
  1125. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1126. }
  1127. catch (Exception ex)
  1128. {
  1129. Logger.LogError(ex, "Error sending server shutdown notification");
  1130. }
  1131. ShutdownInternal();
  1132. }
  1133. protected abstract void ShutdownInternal();
  1134. public event EventHandler HasUpdateAvailableChanged;
  1135. private bool _hasUpdateAvailable;
  1136. public bool HasUpdateAvailable
  1137. {
  1138. get => _hasUpdateAvailable;
  1139. set
  1140. {
  1141. var fireEvent = value && !_hasUpdateAvailable;
  1142. _hasUpdateAvailable = value;
  1143. if (fireEvent)
  1144. {
  1145. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1146. }
  1147. }
  1148. }
  1149. /// <summary>
  1150. /// Removes the plugin.
  1151. /// </summary>
  1152. /// <param name="plugin">The plugin.</param>
  1153. public void RemovePlugin(IPlugin plugin)
  1154. {
  1155. var list = _plugins.ToList();
  1156. list.Remove(plugin);
  1157. _plugins = list.ToArray();
  1158. }
  1159. public IEnumerable<Assembly> GetApiPluginAssemblies()
  1160. {
  1161. var assemblies = _allConcreteTypes
  1162. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  1163. .Select(i => i.Assembly)
  1164. .Distinct();
  1165. foreach (var assembly in assemblies)
  1166. {
  1167. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  1168. yield return assembly;
  1169. }
  1170. }
  1171. public virtual void LaunchUrl(string url)
  1172. {
  1173. if (!CanLaunchWebBrowser)
  1174. {
  1175. throw new NotSupportedException();
  1176. }
  1177. var process = new Process
  1178. {
  1179. StartInfo = new ProcessStartInfo
  1180. {
  1181. FileName = url,
  1182. UseShellExecute = true,
  1183. ErrorDialog = false
  1184. },
  1185. EnableRaisingEvents = true
  1186. };
  1187. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1188. try
  1189. {
  1190. process.Start();
  1191. }
  1192. catch (Exception ex)
  1193. {
  1194. Logger.LogError(ex, "Error launching url: {url}", url);
  1195. throw;
  1196. }
  1197. }
  1198. private bool _disposed = false;
  1199. /// <summary>
  1200. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1201. /// </summary>
  1202. public void Dispose()
  1203. {
  1204. Dispose(true);
  1205. GC.SuppressFinalize(this);
  1206. }
  1207. /// <summary>
  1208. /// Releases unmanaged and - optionally - managed resources.
  1209. /// </summary>
  1210. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1211. protected virtual void Dispose(bool dispose)
  1212. {
  1213. if (_disposed)
  1214. {
  1215. return;
  1216. }
  1217. if (dispose)
  1218. {
  1219. var type = GetType();
  1220. Logger.LogInformation("Disposing {Type}", type.Name);
  1221. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1222. _disposableParts.Clear();
  1223. foreach (var part in parts)
  1224. {
  1225. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1226. try
  1227. {
  1228. part.Dispose();
  1229. }
  1230. catch (Exception ex)
  1231. {
  1232. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1233. }
  1234. }
  1235. }
  1236. _disposed = true;
  1237. }
  1238. }
  1239. internal class CertificateInfo
  1240. {
  1241. public string Path { get; set; }
  1242. public string Password { get; set; }
  1243. }
  1244. }