ApplicationHost.cs 56 KB

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