ApplicationHost.cs 59 KB

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