ApplicationHost.cs 60 KB

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