ApplicationHost.cs 57 KB

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