ApplicationHost.cs 59 KB

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