ApplicationHost.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611
  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.Activity;
  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.Diagnostics;
  33. using Emby.Server.Implementations.Dto;
  34. using Emby.Server.Implementations.HttpServer;
  35. using Emby.Server.Implementations.HttpServer.Security;
  36. using Emby.Server.Implementations.IO;
  37. using Emby.Server.Implementations.Library;
  38. using Emby.Server.Implementations.LiveTv;
  39. using Emby.Server.Implementations.Localization;
  40. using Emby.Server.Implementations.Net;
  41. using Emby.Server.Implementations.Playlists;
  42. using Emby.Server.Implementations.ScheduledTasks;
  43. using Emby.Server.Implementations.Security;
  44. using Emby.Server.Implementations.Serialization;
  45. using Emby.Server.Implementations.Services;
  46. using Emby.Server.Implementations.Session;
  47. using Emby.Server.Implementations.SocketSharp;
  48. using Emby.Server.Implementations.TV;
  49. using Emby.Server.Implementations.Updates;
  50. using Jellyfin.Drawing.Skia;
  51. using MediaBrowser.Api;
  52. using MediaBrowser.Common;
  53. using MediaBrowser.Common.Configuration;
  54. using MediaBrowser.Common.Events;
  55. using MediaBrowser.Common.Net;
  56. using MediaBrowser.Common.Plugins;
  57. using MediaBrowser.Common.Updates;
  58. using MediaBrowser.Controller;
  59. using MediaBrowser.Controller.Authentication;
  60. using MediaBrowser.Controller.Channels;
  61. using MediaBrowser.Controller.Chapters;
  62. using MediaBrowser.Controller.Collections;
  63. using MediaBrowser.Controller.Configuration;
  64. using MediaBrowser.Controller.Devices;
  65. using MediaBrowser.Controller.Dlna;
  66. using MediaBrowser.Controller.Drawing;
  67. using MediaBrowser.Controller.Dto;
  68. using MediaBrowser.Controller.Entities;
  69. using MediaBrowser.Controller.Library;
  70. using MediaBrowser.Controller.LiveTv;
  71. using MediaBrowser.Controller.MediaEncoding;
  72. using MediaBrowser.Controller.Net;
  73. using MediaBrowser.Controller.Notifications;
  74. using MediaBrowser.Controller.Persistence;
  75. using MediaBrowser.Controller.Playlists;
  76. using MediaBrowser.Controller.Plugins;
  77. using MediaBrowser.Controller.Providers;
  78. using MediaBrowser.Controller.Resolvers;
  79. using MediaBrowser.Controller.Security;
  80. using MediaBrowser.Controller.Session;
  81. using MediaBrowser.Controller.Sorting;
  82. using MediaBrowser.Controller.Subtitles;
  83. using MediaBrowser.Controller.TV;
  84. using MediaBrowser.LocalMetadata.Savers;
  85. using MediaBrowser.MediaEncoding.BdInfo;
  86. using MediaBrowser.Model.Activity;
  87. using MediaBrowser.Model.Configuration;
  88. using MediaBrowser.Model.Cryptography;
  89. using MediaBrowser.Model.Diagnostics;
  90. using MediaBrowser.Model.Dlna;
  91. using MediaBrowser.Model.Events;
  92. using MediaBrowser.Model.Globalization;
  93. using MediaBrowser.Model.IO;
  94. using MediaBrowser.Model.MediaInfo;
  95. using MediaBrowser.Model.Net;
  96. using MediaBrowser.Model.Serialization;
  97. using MediaBrowser.Model.Services;
  98. using MediaBrowser.Model.System;
  99. using MediaBrowser.Model.Tasks;
  100. using MediaBrowser.Model.Updates;
  101. using MediaBrowser.Providers.Chapters;
  102. using MediaBrowser.Providers.Manager;
  103. using MediaBrowser.Providers.Plugins.TheTvdb;
  104. using MediaBrowser.Providers.Subtitles;
  105. using MediaBrowser.WebDashboard.Api;
  106. using MediaBrowser.XbmcMetadata.Providers;
  107. using Microsoft.AspNetCore.Http;
  108. using Microsoft.AspNetCore.Http.Extensions;
  109. using Microsoft.Extensions.Configuration;
  110. using Microsoft.Extensions.DependencyInjection;
  111. using Microsoft.Extensions.Logging;
  112. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  113. namespace Emby.Server.Implementations
  114. {
  115. /// <summary>
  116. /// Class CompositionRoot.
  117. /// </summary>
  118. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  119. {
  120. private SqliteUserRepository _userRepository;
  121. private IMediaEncoder _mediaEncoder;
  122. private ISessionManager _sessionManager;
  123. private IHttpServer _httpServer;
  124. private IHttpClient _httpClient;
  125. /// <summary>
  126. /// Gets a value indicating whether this instance can self restart.
  127. /// </summary>
  128. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  129. public abstract bool CanSelfRestart { get; }
  130. public virtual bool CanLaunchWebBrowser
  131. {
  132. get
  133. {
  134. if (!Environment.UserInteractive)
  135. {
  136. return false;
  137. }
  138. if (StartupOptions.IsService)
  139. {
  140. return false;
  141. }
  142. if (OperatingSystem.Id == OperatingSystemId.Windows
  143. || OperatingSystem.Id == OperatingSystemId.Darwin)
  144. {
  145. return true;
  146. }
  147. return false;
  148. }
  149. }
  150. /// <summary>
  151. /// Occurs when [has pending restart changed].
  152. /// </summary>
  153. public event EventHandler HasPendingRestartChanged;
  154. /// <summary>
  155. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  156. /// </summary>
  157. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  158. public bool HasPendingRestart { get; private set; }
  159. /// <inheritdoc />
  160. public bool IsShuttingDown { get; private set; }
  161. /// <summary>
  162. /// Gets the logger.
  163. /// </summary>
  164. protected ILogger Logger { get; }
  165. private IPlugin[] _plugins;
  166. /// <summary>
  167. /// Gets the plugins.
  168. /// </summary>
  169. /// <value>The plugins.</value>
  170. public IReadOnlyList<IPlugin> Plugins => _plugins;
  171. /// <summary>
  172. /// Gets the logger factory.
  173. /// </summary>
  174. protected ILoggerFactory LoggerFactory { get; }
  175. /// <summary>
  176. /// Gets or sets the application paths.
  177. /// </summary>
  178. /// <value>The application paths.</value>
  179. protected ServerApplicationPaths ApplicationPaths { get; set; }
  180. /// <summary>
  181. /// Gets or sets all concrete types.
  182. /// </summary>
  183. /// <value>All concrete types.</value>
  184. private Type[] _allConcreteTypes;
  185. /// <summary>
  186. /// The disposable parts.
  187. /// </summary>
  188. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  189. /// <summary>
  190. /// Gets the configuration manager.
  191. /// </summary>
  192. /// <value>The configuration manager.</value>
  193. protected IConfigurationManager ConfigurationManager { get; set; }
  194. public IFileSystem FileSystemManager { get; set; }
  195. /// <inheritdoc />
  196. public PackageVersionClass SystemUpdateLevel
  197. {
  198. get
  199. {
  200. #if BETA
  201. return PackageVersionClass.Beta;
  202. #else
  203. return PackageVersionClass.Release;
  204. #endif
  205. }
  206. }
  207. /// <summary>
  208. /// Gets or sets the service provider.
  209. /// </summary>
  210. public IServiceProvider ServiceProvider { get; set; }
  211. /// <summary>
  212. /// Gets the http port for the webhost.
  213. /// </summary>
  214. public int HttpPort { get; private set; }
  215. /// <summary>
  216. /// Gets the https port for the webhost.
  217. /// </summary>
  218. public int HttpsPort { get; private set; }
  219. /// <summary>
  220. /// Gets the server configuration manager.
  221. /// </summary>
  222. /// <value>The server configuration manager.</value>
  223. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  224. /// <summary>
  225. /// Gets the installation manager.
  226. /// </summary>
  227. /// <value>The installation manager.</value>
  228. protected IInstallationManager InstallationManager { get; private set; }
  229. public IStartupOptions StartupOptions { get; }
  230. protected readonly IXmlSerializer XmlSerializer;
  231. protected INetworkManager NetworkManager { get; set; }
  232. /// <summary>
  233. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  234. /// </summary>
  235. public ApplicationHost(
  236. ServerApplicationPaths applicationPaths,
  237. ILoggerFactory loggerFactory,
  238. IStartupOptions options,
  239. IFileSystem fileSystem,
  240. INetworkManager networkManager)
  241. {
  242. XmlSerializer = new MyXmlSerializer();
  243. NetworkManager = networkManager;
  244. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  245. ApplicationPaths = applicationPaths;
  246. LoggerFactory = loggerFactory;
  247. FileSystemManager = fileSystem;
  248. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager);
  249. Logger = LoggerFactory.CreateLogger("App");
  250. StartupOptions = options;
  251. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  252. NetworkManager.NetworkChanged += OnNetworkChanged;
  253. CertificateInfo = new CertificateInfo
  254. {
  255. Path = ServerConfigurationManager.Configuration.CertificatePath,
  256. Password = ServerConfigurationManager.Configuration.CertificatePassword
  257. };
  258. Certificate = GetCertificate(CertificateInfo);
  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; } = typeof(ApplicationHost).Assembly.GetName().Version;
  282. /// <inheritdoc />
  283. public string ApplicationVersionString { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
  284. /// <summary>
  285. /// Gets the current application user agent.
  286. /// </summary>
  287. /// <value>The application user agent.</value>
  288. public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  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. _httpServer.GlobalResponse = null;
  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(IServiceCollection serviceCollection)
  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.AppendLine(
  431. string.Format(
  432. CultureInfo.InvariantCulture,
  433. "{0} {1}",
  434. plugin.Name,
  435. plugin.Version));
  436. }
  437. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  438. }
  439. DiscoverTypes();
  440. RegisterServices(serviceCollection);
  441. }
  442. public async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func<Task> next)
  443. {
  444. if (!context.WebSockets.IsWebSocketRequest)
  445. {
  446. await next().ConfigureAwait(false);
  447. return;
  448. }
  449. await _httpServer.ProcessWebSocketRequest(context).ConfigureAwait(false);
  450. }
  451. public async Task ExecuteHttpHandlerAsync(HttpContext context, Func<Task> next)
  452. {
  453. if (context.WebSockets.IsWebSocketRequest)
  454. {
  455. await next().ConfigureAwait(false);
  456. return;
  457. }
  458. var request = context.Request;
  459. var response = context.Response;
  460. var localPath = context.Request.Path.ToString();
  461. var req = new WebSocketSharpRequest(request, response, request.Path, LoggerFactory.CreateLogger<WebSocketSharpRequest>());
  462. await _httpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted).ConfigureAwait(false);
  463. }
  464. /// <summary>
  465. /// Registers services/resources with the service collection that will be available via DI.
  466. /// </summary>
  467. protected void RegisterServices(IServiceCollection serviceCollection)
  468. {
  469. var imageEncoderType = SkiaEncoder.IsNativeLibAvailable()
  470. ? typeof(SkiaEncoder)
  471. : typeof(NullImageEncoder);
  472. serviceCollection.AddSingleton(typeof(IImageEncoder), imageEncoderType);
  473. serviceCollection.AddMemoryCache();
  474. serviceCollection.AddSingleton(ConfigurationManager);
  475. serviceCollection.AddSingleton<IApplicationHost>(this);
  476. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  477. serviceCollection.AddSingleton<IJsonSerializer, JsonSerializer>();
  478. // TODO: Remove support for injecting ILogger completely
  479. serviceCollection.AddSingleton((provider) =>
  480. {
  481. Logger.LogWarning("Injecting ILogger directly is deprecated and should be replaced with ILogger<T>");
  482. return Logger;
  483. });
  484. serviceCollection.AddSingleton(FileSystemManager);
  485. serviceCollection.AddSingleton<TvdbClientManager>();
  486. serviceCollection.AddSingleton<IHttpClient, HttpClientManager.HttpClientManager>();
  487. serviceCollection.AddSingleton(NetworkManager);
  488. serviceCollection.AddSingleton<IIsoManager, IsoManager>();
  489. serviceCollection.AddSingleton<ITaskManager, TaskManager>();
  490. serviceCollection.AddSingleton(XmlSerializer);
  491. serviceCollection.AddSingleton<IProcessFactory, ProcessFactory>();
  492. serviceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  493. serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  494. serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  495. serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  496. serviceCollection.AddSingleton<IZipClient, ZipClient>();
  497. serviceCollection.AddSingleton<IHttpResultFactory, HttpResultFactory>();
  498. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  499. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  500. serviceCollection.AddSingleton(ServerConfigurationManager);
  501. serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  502. serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  503. serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  504. serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  505. serviceCollection.AddSingleton<IDisplayPreferencesRepository, SqliteDisplayPreferencesRepository>();
  506. serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  507. serviceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  508. serviceCollection.AddSingleton<IUserRepository, SqliteUserRepository>();
  509. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  510. serviceCollection.AddTransient(provider => new Lazy<IDtoService>(provider.GetRequiredService<IDtoService>));
  511. serviceCollection.AddSingleton<IUserManager, UserManager>();
  512. // TODO: Add StartupOptions.FFmpegPath to IConfiguration so this doesn't need to be constructed manually
  513. serviceCollection.AddSingleton<IMediaEncoder>(provider =>
  514. new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  515. provider.GetRequiredService<ILogger<MediaBrowser.MediaEncoding.Encoder.MediaEncoder>>(),
  516. provider.GetRequiredService<IServerConfigurationManager>(),
  517. provider.GetRequiredService<IFileSystem>(),
  518. provider.GetRequiredService<IProcessFactory>(),
  519. provider.GetRequiredService<ILocalizationManager>(),
  520. provider.GetRequiredService<ISubtitleEncoder>,
  521. provider.GetRequiredService<IConfiguration>(),
  522. StartupOptions.FFmpegPath));
  523. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  524. serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  525. serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  526. serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  527. serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  528. serviceCollection.AddSingleton<IMusicManager, MusicManager>();
  529. serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  530. serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  531. serviceCollection.AddSingleton<ServiceController>();
  532. serviceCollection.AddSingleton<IHttpListener, WebSocketSharpListener>();
  533. serviceCollection.AddSingleton<IHttpServer, HttpListenerHost>();
  534. serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  535. serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  536. serviceCollection.AddSingleton<IDeviceManager, DeviceManager>();
  537. serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  538. serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  539. serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
  540. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  541. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  542. serviceCollection.AddSingleton<IDtoService, DtoService>();
  543. serviceCollection.AddSingleton<IChannelManager, ChannelManager>();
  544. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  545. serviceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  546. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  547. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  548. serviceCollection.AddSingleton<LiveTvDtoService>();
  549. serviceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  550. serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  551. serviceCollection.AddSingleton<INotificationManager, NotificationManager>();
  552. serviceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  553. serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
  554. serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  555. serviceCollection.AddSingleton<IActivityRepository, ActivityRepository>();
  556. serviceCollection.AddSingleton<IActivityManager, ActivityManager>();
  557. serviceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  558. serviceCollection.AddSingleton<ISessionContext, SessionContext>();
  559. serviceCollection.AddSingleton<IAuthService, AuthService>();
  560. serviceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  561. serviceCollection.AddSingleton<IResourceFileManager, ResourceFileManager>();
  562. serviceCollection.AddSingleton<EncodingHelper>();
  563. serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  564. }
  565. /// <summary>
  566. /// Create services registered with the service container that need to be initialized at application startup.
  567. /// </summary>
  568. /// <returns>A task representing the service initialization operation.</returns>
  569. public async Task InitializeServices()
  570. {
  571. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  572. await localizationManager.LoadAll().ConfigureAwait(false);
  573. _mediaEncoder = Resolve<IMediaEncoder>();
  574. _sessionManager = Resolve<ISessionManager>();
  575. _httpServer = Resolve<IHttpServer>();
  576. _httpClient = Resolve<IHttpClient>();
  577. ((SqliteDisplayPreferencesRepository)Resolve<IDisplayPreferencesRepository>()).Initialize();
  578. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  579. ((SqliteUserRepository)Resolve<IUserRepository>()).Initialize();
  580. ((ActivityRepository)Resolve<IActivityRepository>()).Initialize();
  581. SetStaticProperties();
  582. var userManager = (UserManager)Resolve<IUserManager>();
  583. userManager.Initialize();
  584. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  585. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, userManager);
  586. FindParts();
  587. }
  588. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  589. {
  590. // Distinct these to prevent users from reporting problems that aren't actually problems
  591. var commandLineArgs = Environment
  592. .GetCommandLineArgs()
  593. .Distinct();
  594. // Get all 'JELLYFIN_' prefixed environment variables
  595. var allEnvVars = Environment.GetEnvironmentVariables();
  596. var jellyfinEnvVars = new Dictionary<object, object>();
  597. foreach (var key in allEnvVars.Keys)
  598. {
  599. if (key.ToString().StartsWith("JELLYFIN_", StringComparison.OrdinalIgnoreCase))
  600. {
  601. jellyfinEnvVars.Add(key, allEnvVars[key]);
  602. }
  603. }
  604. logger.LogInformation("Environment Variables: {EnvVars}", jellyfinEnvVars);
  605. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  606. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  607. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  608. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  609. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  610. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  611. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  612. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  613. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  614. }
  615. private X509Certificate2 GetCertificate(CertificateInfo info)
  616. {
  617. var certificateLocation = info?.Path;
  618. if (string.IsNullOrWhiteSpace(certificateLocation))
  619. {
  620. return null;
  621. }
  622. try
  623. {
  624. if (!File.Exists(certificateLocation))
  625. {
  626. return null;
  627. }
  628. // Don't use an empty string password
  629. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  630. var localCert = new X509Certificate2(certificateLocation, password);
  631. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  632. if (!localCert.HasPrivateKey)
  633. {
  634. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  635. return null;
  636. }
  637. return localCert;
  638. }
  639. catch (Exception ex)
  640. {
  641. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  642. return null;
  643. }
  644. }
  645. /// <summary>
  646. /// Dirty hacks.
  647. /// </summary>
  648. private void SetStaticProperties()
  649. {
  650. // For now there's no real way to inject these properly
  651. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  652. BaseItem.ConfigurationManager = ServerConfigurationManager;
  653. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  654. BaseItem.ProviderManager = Resolve<IProviderManager>();
  655. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  656. BaseItem.ItemRepository = Resolve<IItemRepository>();
  657. User.UserManager = Resolve<IUserManager>();
  658. BaseItem.FileSystem = FileSystemManager;
  659. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  660. BaseItem.ChannelManager = Resolve<IChannelManager>();
  661. Video.LiveTvManager = Resolve<ILiveTvManager>();
  662. Folder.UserViewManager = Resolve<IUserViewManager>();
  663. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  664. UserView.CollectionManager = Resolve<ICollectionManager>();
  665. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  666. CollectionFolder.XmlSerializer = XmlSerializer;
  667. CollectionFolder.JsonSerializer = Resolve<IJsonSerializer>();
  668. CollectionFolder.ApplicationHost = this;
  669. AuthenticatedAttribute.AuthService = Resolve<IAuthService>();
  670. }
  671. private async void PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> args)
  672. {
  673. string dir = Path.Combine(ApplicationPaths.PluginsPath, args.Argument.name);
  674. var types = Directory.EnumerateFiles(dir, "*.dll", SearchOption.AllDirectories)
  675. .Select(Assembly.LoadFrom)
  676. .SelectMany(x => x.ExportedTypes)
  677. .Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface && !x.IsGenericType)
  678. .ToArray();
  679. int oldLen = _allConcreteTypes.Length;
  680. Array.Resize(ref _allConcreteTypes, oldLen + types.Length);
  681. types.CopyTo(_allConcreteTypes, oldLen);
  682. var plugins = types.Where(x => x.IsAssignableFrom(typeof(IPlugin)))
  683. .Select(CreateInstanceSafe)
  684. .Where(x => x != null)
  685. .Cast<IPlugin>()
  686. .Select(LoadPlugin)
  687. .Where(x => x != null)
  688. .ToArray();
  689. oldLen = _plugins.Length;
  690. Array.Resize(ref _plugins, oldLen + plugins.Length);
  691. plugins.CopyTo(_plugins, oldLen);
  692. var entries = types.Where(x => x.IsAssignableFrom(typeof(IServerEntryPoint)))
  693. .Select(CreateInstanceSafe)
  694. .Where(x => x != null)
  695. .Cast<IServerEntryPoint>()
  696. .ToList();
  697. await Task.WhenAll(StartEntryPoints(entries, true)).ConfigureAwait(false);
  698. await Task.WhenAll(StartEntryPoints(entries, false)).ConfigureAwait(false);
  699. }
  700. /// <summary>
  701. /// Finds plugin components and register them with the appropriate services.
  702. /// </summary>
  703. private void FindParts()
  704. {
  705. InstallationManager = ServiceProvider.GetService<IInstallationManager>();
  706. InstallationManager.PluginInstalled += PluginInstalled;
  707. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  708. {
  709. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  710. ConfigurationManager.SaveConfiguration();
  711. }
  712. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  713. _plugins = GetExports<IPlugin>()
  714. .Select(LoadPlugin)
  715. .Where(i => i != null)
  716. .ToArray();
  717. _httpServer.Init(GetExportTypes<IService>(), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  718. Resolve<ILibraryManager>().AddParts(
  719. GetExports<IResolverIgnoreRule>(),
  720. GetExports<IItemResolver>(),
  721. GetExports<IIntroProvider>(),
  722. GetExports<IBaseItemComparer>(),
  723. GetExports<ILibraryPostScanTask>());
  724. Resolve<IProviderManager>().AddParts(
  725. GetExports<IImageProvider>(),
  726. GetExports<IMetadataService>(),
  727. GetExports<IMetadataProvider>(),
  728. GetExports<IMetadataSaver>(),
  729. GetExports<IExternalId>());
  730. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  731. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  732. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  733. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  734. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  735. Resolve<IUserManager>().AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  736. Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>());
  737. }
  738. private IPlugin LoadPlugin(IPlugin plugin)
  739. {
  740. try
  741. {
  742. if (plugin is IPluginAssembly assemblyPlugin)
  743. {
  744. var assembly = plugin.GetType().Assembly;
  745. var assemblyName = assembly.GetName();
  746. var assemblyFilePath = assembly.Location;
  747. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  748. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  749. try
  750. {
  751. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  752. if (idAttributes.Length > 0)
  753. {
  754. var attribute = (GuidAttribute)idAttributes[0];
  755. var assemblyId = new Guid(attribute.Value);
  756. assemblyPlugin.SetId(assemblyId);
  757. }
  758. }
  759. catch (Exception ex)
  760. {
  761. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  762. }
  763. }
  764. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  765. {
  766. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  767. }
  768. }
  769. catch (Exception ex)
  770. {
  771. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  772. return null;
  773. }
  774. return plugin;
  775. }
  776. /// <summary>
  777. /// Discovers the types.
  778. /// </summary>
  779. protected void DiscoverTypes()
  780. {
  781. Logger.LogInformation("Loading assemblies");
  782. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  783. }
  784. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  785. {
  786. foreach (var ass in assemblies)
  787. {
  788. Type[] exportedTypes;
  789. try
  790. {
  791. exportedTypes = ass.GetExportedTypes();
  792. }
  793. catch (FileNotFoundException ex)
  794. {
  795. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  796. continue;
  797. }
  798. foreach (Type type in exportedTypes)
  799. {
  800. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  801. {
  802. yield return type;
  803. }
  804. }
  805. }
  806. }
  807. private CertificateInfo CertificateInfo { get; set; }
  808. public X509Certificate2 Certificate { get; private set; }
  809. private IEnumerable<string> GetUrlPrefixes()
  810. {
  811. var hosts = new[] { "+" };
  812. return hosts.SelectMany(i =>
  813. {
  814. var prefixes = new List<string>
  815. {
  816. "http://" + i + ":" + HttpPort + "/"
  817. };
  818. if (CertificateInfo != null)
  819. {
  820. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  821. }
  822. return prefixes;
  823. });
  824. }
  825. /// <summary>
  826. /// Called when [configuration updated].
  827. /// </summary>
  828. /// <param name="sender">The sender.</param>
  829. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  830. protected void OnConfigurationUpdated(object sender, EventArgs e)
  831. {
  832. var requiresRestart = false;
  833. // Don't do anything if these haven't been set yet
  834. if (HttpPort != 0 && HttpsPort != 0)
  835. {
  836. // Need to restart if ports have changed
  837. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  838. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  839. {
  840. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  841. {
  842. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  843. ServerConfigurationManager.SaveConfiguration();
  844. requiresRestart = true;
  845. }
  846. }
  847. }
  848. if (!_httpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  849. {
  850. requiresRestart = true;
  851. }
  852. var currentCertPath = CertificateInfo?.Path;
  853. var newCertPath = ServerConfigurationManager.Configuration.CertificatePath;
  854. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  855. {
  856. requiresRestart = true;
  857. }
  858. if (requiresRestart)
  859. {
  860. Logger.LogInformation("App needs to be restarted due to configuration change.");
  861. NotifyPendingRestart();
  862. }
  863. }
  864. /// <summary>
  865. /// Notifies that the kernel that a change has been made that requires a restart
  866. /// </summary>
  867. public void NotifyPendingRestart()
  868. {
  869. Logger.LogInformation("App needs to be restarted.");
  870. var changed = !HasPendingRestart;
  871. HasPendingRestart = true;
  872. if (changed)
  873. {
  874. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  875. }
  876. }
  877. /// <summary>
  878. /// Restarts this instance.
  879. /// </summary>
  880. public void Restart()
  881. {
  882. if (!CanSelfRestart)
  883. {
  884. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  885. }
  886. if (IsShuttingDown)
  887. {
  888. return;
  889. }
  890. IsShuttingDown = true;
  891. Task.Run(async () =>
  892. {
  893. try
  894. {
  895. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  896. }
  897. catch (Exception ex)
  898. {
  899. Logger.LogError(ex, "Error sending server restart notification");
  900. }
  901. Logger.LogInformation("Calling RestartInternal");
  902. RestartInternal();
  903. });
  904. }
  905. protected abstract void RestartInternal();
  906. /// <summary>
  907. /// Gets the composable part assemblies.
  908. /// </summary>
  909. /// <returns>IEnumerable{Assembly}.</returns>
  910. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  911. {
  912. if (Directory.Exists(ApplicationPaths.PluginsPath))
  913. {
  914. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  915. {
  916. Assembly plugAss;
  917. try
  918. {
  919. plugAss = Assembly.LoadFrom(file);
  920. }
  921. catch (FileLoadException ex)
  922. {
  923. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  924. continue;
  925. }
  926. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  927. yield return plugAss;
  928. }
  929. }
  930. // Include composable parts in the Api assembly
  931. yield return typeof(ApiEntryPoint).Assembly;
  932. // Include composable parts in the Dashboard assembly
  933. yield return typeof(DashboardService).Assembly;
  934. // Include composable parts in the Model assembly
  935. yield return typeof(SystemInfo).Assembly;
  936. // Include composable parts in the Common assembly
  937. yield return typeof(IApplicationHost).Assembly;
  938. // Include composable parts in the Controller assembly
  939. yield return typeof(IServerApplicationHost).Assembly;
  940. // Include composable parts in the Providers assembly
  941. yield return typeof(ProviderUtils).Assembly;
  942. // Include composable parts in the Photos assembly
  943. yield return typeof(PhotoProvider).Assembly;
  944. // Emby.Server implementations
  945. yield return typeof(InstallationManager).Assembly;
  946. // MediaEncoding
  947. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  948. // Dlna
  949. yield return typeof(DlnaEntryPoint).Assembly;
  950. // Local metadata
  951. yield return typeof(BoxSetXmlSaver).Assembly;
  952. // Notifications
  953. yield return typeof(NotificationManager).Assembly;
  954. // Xbmc
  955. yield return typeof(ArtistNfoProvider).Assembly;
  956. foreach (var i in GetAssembliesWithPartsInternal())
  957. {
  958. yield return i;
  959. }
  960. }
  961. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  962. /// <summary>
  963. /// Gets the system status.
  964. /// </summary>
  965. /// <param name="cancellationToken">The cancellation token.</param>
  966. /// <returns>SystemInfo.</returns>
  967. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  968. {
  969. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  970. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  971. return new SystemInfo
  972. {
  973. HasPendingRestart = HasPendingRestart,
  974. IsShuttingDown = IsShuttingDown,
  975. Version = ApplicationVersionString,
  976. WebSocketPortNumber = HttpPort,
  977. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  978. Id = SystemId,
  979. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  980. WebPath = ApplicationPaths.WebPath,
  981. LogPath = ApplicationPaths.LogDirectoryPath,
  982. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  983. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  984. CachePath = ApplicationPaths.CachePath,
  985. HttpServerPortNumber = HttpPort,
  986. SupportsHttps = SupportsHttps,
  987. HttpsPortNumber = HttpsPort,
  988. OperatingSystem = OperatingSystem.Id.ToString(),
  989. OperatingSystemDisplayName = OperatingSystem.Name,
  990. CanSelfRestart = CanSelfRestart,
  991. CanLaunchWebBrowser = CanLaunchWebBrowser,
  992. HasUpdateAvailable = HasUpdateAvailable,
  993. TranscodingTempPath = transcodingTempPath,
  994. ServerName = FriendlyName,
  995. LocalAddress = localAddress,
  996. SupportsLibraryMonitor = true,
  997. EncoderLocation = _mediaEncoder.EncoderLocation,
  998. SystemArchitecture = RuntimeInformation.OSArchitecture,
  999. SystemUpdateLevel = SystemUpdateLevel,
  1000. PackageName = StartupOptions.PackageName
  1001. };
  1002. }
  1003. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  1004. => NetworkManager.GetMacAddresses()
  1005. .Select(i => new WakeOnLanInfo(i))
  1006. .ToList();
  1007. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1008. {
  1009. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1010. return new PublicSystemInfo
  1011. {
  1012. Version = ApplicationVersionString,
  1013. ProductName = ApplicationProductName,
  1014. Id = SystemId,
  1015. OperatingSystem = OperatingSystem.Id.ToString(),
  1016. ServerName = FriendlyName,
  1017. LocalAddress = localAddress
  1018. };
  1019. }
  1020. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1021. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1022. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1023. {
  1024. try
  1025. {
  1026. // Return the first matched address, if found, or the first known local address
  1027. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1028. foreach (var address in addresses)
  1029. {
  1030. return GetLocalApiUrl(address);
  1031. }
  1032. return null;
  1033. }
  1034. catch (Exception ex)
  1035. {
  1036. Logger.LogError(ex, "Error getting local Ip address information");
  1037. }
  1038. return null;
  1039. }
  1040. /// <summary>
  1041. /// Removes the scope id from IPv6 addresses.
  1042. /// </summary>
  1043. /// <param name="address">The IPv6 address.</param>
  1044. /// <returns>The IPv6 address without the scope id.</returns>
  1045. private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
  1046. {
  1047. var index = address.IndexOf('%');
  1048. if (index == -1)
  1049. {
  1050. return address;
  1051. }
  1052. return address.Slice(0, index);
  1053. }
  1054. /// <inheritdoc />
  1055. public string GetLocalApiUrl(IPAddress ipAddress)
  1056. {
  1057. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1058. {
  1059. var str = RemoveScopeId(ipAddress.ToString());
  1060. Span<char> span = new char[str.Length + 2];
  1061. span[0] = '[';
  1062. str.CopyTo(span.Slice(1));
  1063. span[^1] = ']';
  1064. return GetLocalApiUrl(span);
  1065. }
  1066. return GetLocalApiUrl(ipAddress.ToString());
  1067. }
  1068. /// <inheritdoc />
  1069. public string GetLocalApiUrl(ReadOnlySpan<char> host)
  1070. {
  1071. var url = new StringBuilder(64);
  1072. url.Append(EnableHttps ? "https://" : "http://")
  1073. .Append(host)
  1074. .Append(':')
  1075. .Append(EnableHttps ? HttpsPort : HttpPort);
  1076. string baseUrl = ServerConfigurationManager.Configuration.BaseUrl;
  1077. if (baseUrl.Length != 0)
  1078. {
  1079. url.Append(baseUrl);
  1080. }
  1081. return url.ToString();
  1082. }
  1083. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1084. {
  1085. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1086. }
  1087. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1088. {
  1089. var addresses = ServerConfigurationManager
  1090. .Configuration
  1091. .LocalNetworkAddresses
  1092. .Select(NormalizeConfiguredLocalAddress)
  1093. .Where(i => i != null)
  1094. .ToList();
  1095. if (addresses.Count == 0)
  1096. {
  1097. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1098. }
  1099. var resultList = new List<IPAddress>();
  1100. foreach (var address in addresses)
  1101. {
  1102. if (!allowLoopback)
  1103. {
  1104. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1105. {
  1106. continue;
  1107. }
  1108. }
  1109. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1110. if (valid)
  1111. {
  1112. resultList.Add(address);
  1113. if (limit > 0 && resultList.Count >= limit)
  1114. {
  1115. return resultList;
  1116. }
  1117. }
  1118. }
  1119. return resultList;
  1120. }
  1121. public IPAddress NormalizeConfiguredLocalAddress(string address)
  1122. {
  1123. var index = address.Trim('/').IndexOf('/');
  1124. if (index != -1)
  1125. {
  1126. address = address.Substring(index + 1);
  1127. }
  1128. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1129. {
  1130. return result;
  1131. }
  1132. return null;
  1133. }
  1134. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1135. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1136. {
  1137. if (address.Equals(IPAddress.Loopback)
  1138. || address.Equals(IPAddress.IPv6Loopback))
  1139. {
  1140. return true;
  1141. }
  1142. var apiUrl = GetLocalApiUrl(address);
  1143. apiUrl += "/system/ping";
  1144. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1145. {
  1146. return cachedResult;
  1147. }
  1148. try
  1149. {
  1150. using (var response = await _httpClient.SendAsync(
  1151. new HttpRequestOptions
  1152. {
  1153. Url = apiUrl,
  1154. LogErrorResponseBody = false,
  1155. BufferContent = false,
  1156. CancellationToken = cancellationToken
  1157. }, HttpMethod.Post).ConfigureAwait(false))
  1158. {
  1159. using (var reader = new StreamReader(response.Content))
  1160. {
  1161. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1162. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1163. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1164. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1165. return valid;
  1166. }
  1167. }
  1168. }
  1169. catch (OperationCanceledException)
  1170. {
  1171. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1172. throw;
  1173. }
  1174. catch (Exception ex)
  1175. {
  1176. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1177. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1178. return false;
  1179. }
  1180. }
  1181. public string FriendlyName =>
  1182. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1183. ? Environment.MachineName
  1184. : ServerConfigurationManager.Configuration.ServerName;
  1185. /// <summary>
  1186. /// Shuts down.
  1187. /// </summary>
  1188. public async Task Shutdown()
  1189. {
  1190. if (IsShuttingDown)
  1191. {
  1192. return;
  1193. }
  1194. IsShuttingDown = true;
  1195. try
  1196. {
  1197. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1198. }
  1199. catch (Exception ex)
  1200. {
  1201. Logger.LogError(ex, "Error sending server shutdown notification");
  1202. }
  1203. ShutdownInternal();
  1204. }
  1205. protected abstract void ShutdownInternal();
  1206. public event EventHandler HasUpdateAvailableChanged;
  1207. private bool _hasUpdateAvailable;
  1208. public bool HasUpdateAvailable
  1209. {
  1210. get => _hasUpdateAvailable;
  1211. set
  1212. {
  1213. var fireEvent = value && !_hasUpdateAvailable;
  1214. _hasUpdateAvailable = value;
  1215. if (fireEvent)
  1216. {
  1217. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1218. }
  1219. }
  1220. }
  1221. /// <summary>
  1222. /// Removes the plugin.
  1223. /// </summary>
  1224. /// <param name="plugin">The plugin.</param>
  1225. public void RemovePlugin(IPlugin plugin)
  1226. {
  1227. var list = _plugins.ToList();
  1228. list.Remove(plugin);
  1229. _plugins = list.ToArray();
  1230. }
  1231. public virtual void LaunchUrl(string url)
  1232. {
  1233. if (!CanLaunchWebBrowser)
  1234. {
  1235. throw new NotSupportedException();
  1236. }
  1237. var process = Resolve<IProcessFactory>().Create(new ProcessOptions
  1238. {
  1239. FileName = url,
  1240. EnableRaisingEvents = true,
  1241. UseShellExecute = true,
  1242. ErrorDialog = false
  1243. });
  1244. process.Exited += ProcessExited;
  1245. try
  1246. {
  1247. process.Start();
  1248. }
  1249. catch (Exception ex)
  1250. {
  1251. Logger.LogError(ex, "Error launching url: {url}", url);
  1252. throw;
  1253. }
  1254. }
  1255. private static void ProcessExited(object sender, EventArgs e)
  1256. {
  1257. ((IProcess)sender).Dispose();
  1258. }
  1259. public virtual void EnableLoopback(string appName)
  1260. {
  1261. }
  1262. private bool _disposed = false;
  1263. /// <summary>
  1264. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1265. /// </summary>
  1266. public void Dispose()
  1267. {
  1268. Dispose(true);
  1269. GC.SuppressFinalize(this);
  1270. }
  1271. /// <summary>
  1272. /// Releases unmanaged and - optionally - managed resources.
  1273. /// </summary>
  1274. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1275. protected virtual void Dispose(bool dispose)
  1276. {
  1277. if (_disposed)
  1278. {
  1279. return;
  1280. }
  1281. if (dispose)
  1282. {
  1283. var type = GetType();
  1284. Logger.LogInformation("Disposing {Type}", type.Name);
  1285. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1286. _disposableParts.Clear();
  1287. foreach (var part in parts)
  1288. {
  1289. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1290. try
  1291. {
  1292. part.Dispose();
  1293. }
  1294. catch (Exception ex)
  1295. {
  1296. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1297. }
  1298. }
  1299. _userRepository?.Dispose();
  1300. }
  1301. _userRepository = null;
  1302. _disposed = true;
  1303. }
  1304. }
  1305. internal class CertificateInfo
  1306. {
  1307. public string Path { get; set; }
  1308. public string Password { get; set; }
  1309. }
  1310. }