ApplicationHost.cs 57 KB

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