ApplicationHost.cs 61 KB

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