ApplicationHost.cs 58 KB

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