ApplicationHost.cs 57 KB

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