ApplicationHost.cs 61 KB

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