ApplicationHost.cs 57 KB

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