ApplicationHost.cs 60 KB

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