ApplicationHost.cs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  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. foreach (var plugin in Plugins)
  628. {
  629. Logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version);
  630. }
  631. }
  632. _urlPrefixes = GetUrlPrefixes().ToArray();
  633. Resolve<ILibraryManager>().AddParts(
  634. GetExports<IResolverIgnoreRule>(),
  635. GetExports<IItemResolver>(),
  636. GetExports<IIntroProvider>(),
  637. GetExports<IBaseItemComparer>(),
  638. GetExports<ILibraryPostScanTask>());
  639. Resolve<IProviderManager>().AddParts(
  640. GetExports<IImageProvider>(),
  641. GetExports<IMetadataService>(),
  642. GetExports<IMetadataProvider>(),
  643. GetExports<IMetadataSaver>(),
  644. GetExports<IExternalId>());
  645. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  646. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  647. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  648. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  649. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  650. Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>());
  651. }
  652. /// <summary>
  653. /// Discovers the types.
  654. /// </summary>
  655. protected void DiscoverTypes()
  656. {
  657. Logger.LogInformation("Loading assemblies");
  658. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  659. }
  660. private void RegisterPluginServices()
  661. {
  662. foreach (var pluginServiceRegistrator in GetExportTypes<IPluginServiceRegistrator>())
  663. {
  664. try
  665. {
  666. var instance = (IPluginServiceRegistrator)Activator.CreateInstance(pluginServiceRegistrator);
  667. instance.RegisterServices(ServiceCollection);
  668. }
  669. catch (Exception ex)
  670. {
  671. Logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly);
  672. }
  673. }
  674. }
  675. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  676. {
  677. foreach (var ass in assemblies)
  678. {
  679. Type[] exportedTypes;
  680. try
  681. {
  682. exportedTypes = ass.GetExportedTypes();
  683. }
  684. catch (FileNotFoundException ex)
  685. {
  686. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  687. continue;
  688. }
  689. catch (TypeLoadException ex)
  690. {
  691. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  692. continue;
  693. }
  694. foreach (Type type in exportedTypes)
  695. {
  696. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  697. {
  698. yield return type;
  699. }
  700. }
  701. }
  702. }
  703. private CertificateInfo CertificateInfo { get; set; }
  704. public X509Certificate2 Certificate { get; private set; }
  705. private IEnumerable<string> GetUrlPrefixes()
  706. {
  707. var hosts = new[] { "+" };
  708. return hosts.SelectMany(i =>
  709. {
  710. var prefixes = new List<string>
  711. {
  712. "http://" + i + ":" + HttpPort + "/"
  713. };
  714. if (CertificateInfo != null)
  715. {
  716. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  717. }
  718. return prefixes;
  719. });
  720. }
  721. /// <summary>
  722. /// Called when [configuration updated].
  723. /// </summary>
  724. /// <param name="sender">The sender.</param>
  725. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  726. protected void OnConfigurationUpdated(object sender, EventArgs e)
  727. {
  728. var requiresRestart = false;
  729. // Don't do anything if these haven't been set yet
  730. if (HttpPort != 0 && HttpsPort != 0)
  731. {
  732. var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration();
  733. // Need to restart if ports have changed
  734. if (networkConfiguration.HttpServerPortNumber != HttpPort ||
  735. networkConfiguration.HttpsPortNumber != HttpsPort)
  736. {
  737. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  738. {
  739. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  740. ServerConfigurationManager.SaveConfiguration();
  741. requiresRestart = true;
  742. }
  743. }
  744. }
  745. if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  746. {
  747. requiresRestart = true;
  748. }
  749. var currentCertPath = CertificateInfo?.Path;
  750. var newCertPath = ServerConfigurationManager.Configuration.CertificatePath;
  751. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  752. {
  753. requiresRestart = true;
  754. }
  755. if (requiresRestart)
  756. {
  757. Logger.LogInformation("App needs to be restarted due to configuration change.");
  758. NotifyPendingRestart();
  759. }
  760. }
  761. /// <summary>
  762. /// Notifies that the kernel that a change has been made that requires a restart.
  763. /// </summary>
  764. public void NotifyPendingRestart()
  765. {
  766. Logger.LogInformation("App needs to be restarted.");
  767. var changed = !HasPendingRestart;
  768. HasPendingRestart = true;
  769. if (changed)
  770. {
  771. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  772. }
  773. }
  774. /// <summary>
  775. /// Restarts this instance.
  776. /// </summary>
  777. public void Restart()
  778. {
  779. if (!CanSelfRestart)
  780. {
  781. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  782. }
  783. if (IsShuttingDown)
  784. {
  785. return;
  786. }
  787. IsShuttingDown = true;
  788. Task.Run(async () =>
  789. {
  790. try
  791. {
  792. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  793. }
  794. catch (Exception ex)
  795. {
  796. Logger.LogError(ex, "Error sending server restart notification");
  797. }
  798. Logger.LogInformation("Calling RestartInternal");
  799. RestartInternal();
  800. });
  801. }
  802. protected abstract void RestartInternal();
  803. /// <inheritdoc/>
  804. public IEnumerable<LocalPlugin> GetLocalPlugins(string path, bool cleanup = true)
  805. {
  806. var minimumVersion = new Version(0, 0, 0, 1);
  807. var versions = new List<LocalPlugin>();
  808. if (!Directory.Exists(path))
  809. {
  810. // Plugin path doesn't exist, don't try to enumerate subfolders.
  811. return Enumerable.Empty<LocalPlugin>();
  812. }
  813. var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly);
  814. foreach (var dir in directories)
  815. {
  816. try
  817. {
  818. var metafile = Path.Combine(dir, "meta.json");
  819. if (File.Exists(metafile))
  820. {
  821. var manifest = _jsonSerializer.DeserializeFromFile<PluginManifest>(metafile);
  822. if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
  823. {
  824. targetAbi = minimumVersion;
  825. }
  826. if (!Version.TryParse(manifest.Version, out var version))
  827. {
  828. version = minimumVersion;
  829. }
  830. if (ApplicationVersion >= targetAbi)
  831. {
  832. // Only load Plugins if the plugin is built for this version or below.
  833. versions.Add(new LocalPlugin(manifest.Guid, manifest.Name, version, dir));
  834. }
  835. }
  836. else
  837. {
  838. // No metafile, so lets see if the folder is versioned.
  839. metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
  840. int versionIndex = dir.LastIndexOf('_');
  841. if (versionIndex != -1 && Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version parsedVersion))
  842. {
  843. // Versioned folder.
  844. versions.Add(new LocalPlugin(Guid.Empty, metafile, parsedVersion, dir));
  845. }
  846. else
  847. {
  848. // Un-versioned folder - Add it under the path name and version 0.0.0.1.
  849. versions.Add(new LocalPlugin(Guid.Empty, metafile, minimumVersion, dir));
  850. }
  851. }
  852. }
  853. catch
  854. {
  855. continue;
  856. }
  857. }
  858. string lastName = string.Empty;
  859. versions.Sort(LocalPlugin.Compare);
  860. // Traverse backwards through the list.
  861. // The first item will be the latest version.
  862. for (int x = versions.Count - 1; x >= 0; x--)
  863. {
  864. if (!string.Equals(lastName, versions[x].Name, StringComparison.OrdinalIgnoreCase))
  865. {
  866. versions[x].DllFiles.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories));
  867. lastName = versions[x].Name;
  868. continue;
  869. }
  870. if (!string.IsNullOrEmpty(lastName) && cleanup)
  871. {
  872. // Attempt a cleanup of old folders.
  873. try
  874. {
  875. Logger.LogDebug("Deleting {Path}", versions[x].Path);
  876. Directory.Delete(versions[x].Path, true);
  877. }
  878. catch (Exception e)
  879. {
  880. Logger.LogWarning(e, "Unable to delete {Path}", versions[x].Path);
  881. }
  882. versions.RemoveAt(x);
  883. }
  884. }
  885. return versions;
  886. }
  887. /// <summary>
  888. /// Gets the composable part assemblies.
  889. /// </summary>
  890. /// <returns>IEnumerable{Assembly}.</returns>
  891. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  892. {
  893. if (Directory.Exists(ApplicationPaths.PluginsPath))
  894. {
  895. foreach (var plugin in GetLocalPlugins(ApplicationPaths.PluginsPath))
  896. {
  897. foreach (var file in plugin.DllFiles)
  898. {
  899. Assembly plugAss;
  900. try
  901. {
  902. plugAss = Assembly.LoadFrom(file);
  903. }
  904. catch (FileLoadException ex)
  905. {
  906. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  907. continue;
  908. }
  909. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  910. yield return plugAss;
  911. }
  912. }
  913. }
  914. // Include composable parts in the Model assembly
  915. yield return typeof(SystemInfo).Assembly;
  916. // Include composable parts in the Common assembly
  917. yield return typeof(IApplicationHost).Assembly;
  918. // Include composable parts in the Controller assembly
  919. yield return typeof(IServerApplicationHost).Assembly;
  920. // Include composable parts in the Providers assembly
  921. yield return typeof(ProviderUtils).Assembly;
  922. // Include composable parts in the Photos assembly
  923. yield return typeof(PhotoProvider).Assembly;
  924. // Emby.Server implementations
  925. yield return typeof(InstallationManager).Assembly;
  926. // MediaEncoding
  927. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  928. // Dlna
  929. yield return typeof(DlnaEntryPoint).Assembly;
  930. // Local metadata
  931. yield return typeof(BoxSetXmlSaver).Assembly;
  932. // Notifications
  933. yield return typeof(NotificationManager).Assembly;
  934. // Xbmc
  935. yield return typeof(ArtistNfoProvider).Assembly;
  936. // Network
  937. yield return typeof(NetworkManager).Assembly;
  938. foreach (var i in GetAssembliesWithPartsInternal())
  939. {
  940. yield return i;
  941. }
  942. }
  943. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  944. /// <summary>
  945. /// Gets the system status.
  946. /// </summary>
  947. /// <param name="source">Where this request originated.</param>
  948. /// <returns>SystemInfo.</returns>
  949. public SystemInfo GetSystemInfo(IPAddress source)
  950. {
  951. return new SystemInfo
  952. {
  953. HasPendingRestart = HasPendingRestart,
  954. IsShuttingDown = IsShuttingDown,
  955. Version = ApplicationVersionString,
  956. WebSocketPortNumber = HttpPort,
  957. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  958. Id = SystemId,
  959. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  960. WebPath = ApplicationPaths.WebPath,
  961. LogPath = ApplicationPaths.LogDirectoryPath,
  962. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  963. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  964. CachePath = ApplicationPaths.CachePath,
  965. OperatingSystem = OperatingSystem.Id.ToString(),
  966. OperatingSystemDisplayName = OperatingSystem.Name,
  967. CanSelfRestart = CanSelfRestart,
  968. CanLaunchWebBrowser = CanLaunchWebBrowser,
  969. HasUpdateAvailable = HasUpdateAvailable,
  970. TranscodingTempPath = ConfigurationManager.GetTranscodePath(),
  971. ServerName = FriendlyName,
  972. LocalAddress = GetSmartApiUrl(source),
  973. SupportsLibraryMonitor = true,
  974. EncoderLocation = _mediaEncoder.EncoderLocation,
  975. SystemArchitecture = RuntimeInformation.OSArchitecture,
  976. PackageName = _startupOptions.PackageName
  977. };
  978. }
  979. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  980. => NetManager.GetMacAddresses()
  981. .Select(i => new WakeOnLanInfo(i))
  982. .ToList();
  983. public PublicSystemInfo GetPublicSystemInfo(IPAddress source)
  984. {
  985. return new PublicSystemInfo
  986. {
  987. Version = ApplicationVersionString,
  988. ProductName = ApplicationProductName,
  989. Id = SystemId,
  990. OperatingSystem = OperatingSystem.Id.ToString(),
  991. ServerName = FriendlyName,
  992. LocalAddress = GetSmartApiUrl(source),
  993. StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
  994. };
  995. }
  996. /// <inheritdoc/>
  997. public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.GetNetworkConfiguration().EnableHttps;
  998. /// <inheritdoc/>
  999. public string GetSmartApiUrl(IPAddress ipAddress, int? port = null)
  1000. {
  1001. // Published server ends with a /
  1002. if (_startupOptions.PublishedServerUrl != null)
  1003. {
  1004. // Published server ends with a '/', so we need to remove it.
  1005. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1006. }
  1007. string smart = NetManager.GetBindInterface(ipAddress, out port);
  1008. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1009. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1010. {
  1011. return smart.Trim('/');
  1012. }
  1013. return GetLocalApiUrl(smart.Trim('/'), null, port);
  1014. }
  1015. /// <inheritdoc/>
  1016. public string GetSmartApiUrl(HttpRequest request, int? port = null)
  1017. {
  1018. // Published server ends with a /
  1019. if (_startupOptions.PublishedServerUrl != null)
  1020. {
  1021. // Published server ends with a '/', so we need to remove it.
  1022. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1023. }
  1024. string smart = NetManager.GetBindInterface(request, out port);
  1025. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1026. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1027. {
  1028. return smart.Trim('/');
  1029. }
  1030. return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port);
  1031. }
  1032. /// <inheritdoc/>
  1033. public string GetSmartApiUrl(string hostname, int? port = null)
  1034. {
  1035. // Published server ends with a /
  1036. if (_startupOptions.PublishedServerUrl != null)
  1037. {
  1038. // Published server ends with a '/', so we need to remove it.
  1039. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1040. }
  1041. string smart = NetManager.GetBindInterface(hostname, out port);
  1042. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1043. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1044. {
  1045. return smart.Trim('/');
  1046. }
  1047. return GetLocalApiUrl(smart.Trim('/'), null, port);
  1048. }
  1049. /// <inheritdoc/>
  1050. public string GetLoopbackHttpApiUrl()
  1051. {
  1052. if (NetManager.IsIP6Enabled)
  1053. {
  1054. return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort);
  1055. }
  1056. return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
  1057. }
  1058. /// <inheritdoc/>
  1059. public string GetLocalApiUrl(string host, string scheme = null, int? port = null)
  1060. {
  1061. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  1062. // not. For consistency, always trim the trailing slash.
  1063. return new UriBuilder
  1064. {
  1065. Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
  1066. Host = host,
  1067. Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
  1068. Path = ServerConfigurationManager.GetNetworkConfiguration().BaseUrl
  1069. }.ToString().TrimEnd('/');
  1070. }
  1071. public string FriendlyName =>
  1072. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1073. ? Environment.MachineName
  1074. : ServerConfigurationManager.Configuration.ServerName;
  1075. /// <summary>
  1076. /// Shuts down.
  1077. /// </summary>
  1078. public async Task Shutdown()
  1079. {
  1080. if (IsShuttingDown)
  1081. {
  1082. return;
  1083. }
  1084. IsShuttingDown = true;
  1085. try
  1086. {
  1087. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1088. }
  1089. catch (Exception ex)
  1090. {
  1091. Logger.LogError(ex, "Error sending server shutdown notification");
  1092. }
  1093. ShutdownInternal();
  1094. }
  1095. protected abstract void ShutdownInternal();
  1096. public event EventHandler HasUpdateAvailableChanged;
  1097. private bool _hasUpdateAvailable;
  1098. public bool HasUpdateAvailable
  1099. {
  1100. get => _hasUpdateAvailable;
  1101. set
  1102. {
  1103. var fireEvent = value && !_hasUpdateAvailable;
  1104. _hasUpdateAvailable = value;
  1105. if (fireEvent)
  1106. {
  1107. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1108. }
  1109. }
  1110. }
  1111. /// <summary>
  1112. /// Removes the plugin.
  1113. /// </summary>
  1114. /// <param name="plugin">The plugin.</param>
  1115. public void RemovePlugin(IPlugin plugin)
  1116. {
  1117. var list = _plugins.ToList();
  1118. list.Remove(plugin);
  1119. _plugins = list.ToArray();
  1120. }
  1121. public IEnumerable<Assembly> GetApiPluginAssemblies()
  1122. {
  1123. var assemblies = _allConcreteTypes
  1124. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  1125. .Select(i => i.Assembly)
  1126. .Distinct();
  1127. foreach (var assembly in assemblies)
  1128. {
  1129. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  1130. yield return assembly;
  1131. }
  1132. }
  1133. public virtual void LaunchUrl(string url)
  1134. {
  1135. if (!CanLaunchWebBrowser)
  1136. {
  1137. throw new NotSupportedException();
  1138. }
  1139. var process = new Process
  1140. {
  1141. StartInfo = new ProcessStartInfo
  1142. {
  1143. FileName = url,
  1144. UseShellExecute = true,
  1145. ErrorDialog = false
  1146. },
  1147. EnableRaisingEvents = true
  1148. };
  1149. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1150. try
  1151. {
  1152. process.Start();
  1153. }
  1154. catch (Exception ex)
  1155. {
  1156. Logger.LogError(ex, "Error launching url: {url}", url);
  1157. throw;
  1158. }
  1159. }
  1160. private bool _disposed = false;
  1161. /// <summary>
  1162. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1163. /// </summary>
  1164. public void Dispose()
  1165. {
  1166. Dispose(true);
  1167. GC.SuppressFinalize(this);
  1168. }
  1169. /// <summary>
  1170. /// Releases unmanaged and - optionally - managed resources.
  1171. /// </summary>
  1172. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1173. protected virtual void Dispose(bool dispose)
  1174. {
  1175. if (_disposed)
  1176. {
  1177. return;
  1178. }
  1179. if (dispose)
  1180. {
  1181. var type = GetType();
  1182. Logger.LogInformation("Disposing {Type}", type.Name);
  1183. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1184. _disposableParts.Clear();
  1185. foreach (var part in parts)
  1186. {
  1187. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1188. try
  1189. {
  1190. part.Dispose();
  1191. }
  1192. catch (Exception ex)
  1193. {
  1194. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1195. }
  1196. }
  1197. }
  1198. _disposed = true;
  1199. }
  1200. }
  1201. internal class CertificateInfo
  1202. {
  1203. public string Path { get; set; }
  1204. public string Password { get; set; }
  1205. }
  1206. }