ApplicationHost.cs 55 KB

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