ApplicationHost.cs 59 KB

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