ApplicationHost.cs 56 KB

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