ApplicationHost.cs 57 KB

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