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. public IJsonSerializer JsonSerializer { get; private set; }
  233. /// <summary>
  234. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  235. /// </summary>
  236. public ApplicationHost(
  237. ServerApplicationPaths applicationPaths,
  238. ILoggerFactory loggerFactory,
  239. IStartupOptions options,
  240. IFileSystem fileSystem,
  241. INetworkManager networkManager)
  242. {
  243. XmlSerializer = new MyXmlSerializer();
  244. NetworkManager = networkManager;
  245. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  246. ApplicationPaths = applicationPaths;
  247. LoggerFactory = loggerFactory;
  248. FileSystemManager = fileSystem;
  249. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager);
  250. Logger = LoggerFactory.CreateLogger("App");
  251. StartupOptions = options;
  252. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  253. NetworkManager.NetworkChanged += OnNetworkChanged;
  254. CertificateInfo = new CertificateInfo
  255. {
  256. Path = ServerConfigurationManager.Configuration.CertificatePath,
  257. Password = ServerConfigurationManager.Configuration.CertificatePassword
  258. };
  259. Certificate = GetCertificate(CertificateInfo);
  260. }
  261. public string ExpandVirtualPath(string path)
  262. {
  263. var appPaths = ApplicationPaths;
  264. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  265. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  266. }
  267. public string ReverseVirtualPath(string path)
  268. {
  269. var appPaths = ApplicationPaths;
  270. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  271. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  272. }
  273. private string[] GetConfiguredLocalSubnets()
  274. {
  275. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  276. }
  277. private void OnNetworkChanged(object sender, EventArgs e)
  278. {
  279. _validAddressResults.Clear();
  280. }
  281. /// <inheritdoc />
  282. public Version ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version;
  283. /// <inheritdoc />
  284. public string ApplicationVersionString { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
  285. /// <summary>
  286. /// Gets the current application user agent.
  287. /// </summary>
  288. /// <value>The application user agent.</value>
  289. public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  290. /// <summary>
  291. /// Gets the email address for use within a comment section of a user agent field.
  292. /// Presently used to provide contact information to MusicBrainz service.
  293. /// </summary>
  294. public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
  295. /// <summary>
  296. /// Gets the current application name.
  297. /// </summary>
  298. /// <value>The application name.</value>
  299. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  300. private DeviceId _deviceId;
  301. public string SystemId
  302. {
  303. get
  304. {
  305. if (_deviceId == null)
  306. {
  307. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  308. }
  309. return _deviceId.Value;
  310. }
  311. }
  312. /// <inheritdoc/>
  313. public string Name => ApplicationProductName;
  314. /// <summary>
  315. /// Creates an instance of type and resolves all constructor dependencies.
  316. /// </summary>
  317. /// <param name="type">The type.</param>
  318. /// <returns>System.Object.</returns>
  319. public object CreateInstance(Type type)
  320. => ActivatorUtilities.CreateInstance(ServiceProvider, type);
  321. /// <summary>
  322. /// Creates an instance of type and resolves all constructor dependencies.
  323. /// </summary>
  324. /// /// <typeparam name="T">The type.</typeparam>
  325. /// <returns>T.</returns>
  326. public T CreateInstance<T>()
  327. => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
  328. /// <summary>
  329. /// Creates the instance safe.
  330. /// </summary>
  331. /// <param name="type">The type.</param>
  332. /// <returns>System.Object.</returns>
  333. protected object CreateInstanceSafe(Type type)
  334. {
  335. try
  336. {
  337. Logger.LogDebug("Creating instance of {Type}", type);
  338. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  339. }
  340. catch (Exception ex)
  341. {
  342. Logger.LogError(ex, "Error creating {Type}", type);
  343. return null;
  344. }
  345. }
  346. /// <summary>
  347. /// Resolves this instance.
  348. /// </summary>
  349. /// <typeparam name="T">The type</typeparam>
  350. /// <returns>``0.</returns>
  351. public T Resolve<T>() => ServiceProvider.GetService<T>();
  352. /// <summary>
  353. /// Gets the export types.
  354. /// </summary>
  355. /// <typeparam name="T">The type.</typeparam>
  356. /// <returns>IEnumerable{Type}.</returns>
  357. public IEnumerable<Type> GetExportTypes<T>()
  358. {
  359. var currentType = typeof(T);
  360. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  361. }
  362. /// <inheritdoc />
  363. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  364. {
  365. // Convert to list so this isn't executed for each iteration
  366. var parts = GetExportTypes<T>()
  367. .Select(CreateInstanceSafe)
  368. .Where(i => i != null)
  369. .Cast<T>()
  370. .ToList();
  371. if (manageLifetime)
  372. {
  373. lock (_disposableParts)
  374. {
  375. _disposableParts.AddRange(parts.OfType<IDisposable>());
  376. }
  377. }
  378. return parts;
  379. }
  380. /// <summary>
  381. /// Runs the startup tasks.
  382. /// </summary>
  383. /// <returns><see cref="Task" />.</returns>
  384. public async Task RunStartupTasksAsync()
  385. {
  386. Logger.LogInformation("Running startup tasks");
  387. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  388. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  389. _mediaEncoder.SetFFmpegPath();
  390. Logger.LogInformation("ServerId: {0}", SystemId);
  391. var entryPoints = GetExports<IServerEntryPoint>();
  392. var stopWatch = new Stopwatch();
  393. stopWatch.Start();
  394. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  395. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  396. Logger.LogInformation("Core startup complete");
  397. _httpServer.GlobalResponse = null;
  398. stopWatch.Restart();
  399. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  400. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  401. stopWatch.Stop();
  402. }
  403. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  404. {
  405. foreach (var entryPoint in entryPoints)
  406. {
  407. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  408. {
  409. continue;
  410. }
  411. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  412. yield return entryPoint.RunAsync();
  413. }
  414. }
  415. /// <inheritdoc/>
  416. public void Init(IServiceCollection serviceCollection)
  417. {
  418. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  419. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  420. // Safeguard against invalid configuration
  421. if (HttpPort == HttpsPort)
  422. {
  423. HttpPort = ServerConfiguration.DefaultHttpPort;
  424. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  425. }
  426. JsonSerializer = new JsonSerializer();
  427. if (Plugins != null)
  428. {
  429. var pluginBuilder = new StringBuilder();
  430. foreach (var plugin in Plugins)
  431. {
  432. pluginBuilder.AppendLine(
  433. string.Format(
  434. CultureInfo.InvariantCulture,
  435. "{0} {1}",
  436. plugin.Name,
  437. plugin.Version));
  438. }
  439. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  440. }
  441. DiscoverTypes();
  442. RegisterServices(serviceCollection);
  443. }
  444. public async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func<Task> next)
  445. {
  446. if (!context.WebSockets.IsWebSocketRequest)
  447. {
  448. await next().ConfigureAwait(false);
  449. return;
  450. }
  451. await _httpServer.ProcessWebSocketRequest(context).ConfigureAwait(false);
  452. }
  453. public async Task ExecuteHttpHandlerAsync(HttpContext context, Func<Task> next)
  454. {
  455. if (context.WebSockets.IsWebSocketRequest)
  456. {
  457. await next().ConfigureAwait(false);
  458. return;
  459. }
  460. var request = context.Request;
  461. var response = context.Response;
  462. var localPath = context.Request.Path.ToString();
  463. var req = new WebSocketSharpRequest(request, response, request.Path, LoggerFactory.CreateLogger<WebSocketSharpRequest>());
  464. await _httpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted).ConfigureAwait(false);
  465. }
  466. /// <summary>
  467. /// Registers services/resources with the service collection that will be available via DI.
  468. /// </summary>
  469. protected void RegisterServices(IServiceCollection serviceCollection)
  470. {
  471. var imageEncoderType = SkiaEncoder.IsNativeLibAvailable()
  472. ? typeof(SkiaEncoder)
  473. : typeof(NullImageEncoder);
  474. serviceCollection.AddSingleton(typeof(IImageEncoder), imageEncoderType);
  475. serviceCollection.AddMemoryCache();
  476. serviceCollection.AddSingleton(ConfigurationManager);
  477. serviceCollection.AddSingleton<IApplicationHost>(this);
  478. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  479. serviceCollection.AddSingleton(JsonSerializer);
  480. // TODO: Support for injecting ILogger should be deprecated in favour of ILogger<T> and this removed
  481. serviceCollection.AddSingleton<ILogger>(Logger);
  482. serviceCollection.AddSingleton(FileSystemManager);
  483. serviceCollection.AddSingleton<TvdbClientManager>();
  484. serviceCollection.AddSingleton<IHttpClient, HttpClientManager.HttpClientManager>();
  485. serviceCollection.AddSingleton(NetworkManager);
  486. serviceCollection.AddSingleton<IIsoManager, IsoManager>();
  487. serviceCollection.AddSingleton<ITaskManager, TaskManager>();
  488. serviceCollection.AddSingleton(XmlSerializer);
  489. serviceCollection.AddSingleton<IProcessFactory, ProcessFactory>();
  490. serviceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  491. serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  492. serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  493. serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  494. serviceCollection.AddSingleton<IZipClient, ZipClient>();
  495. serviceCollection.AddSingleton<IHttpResultFactory, HttpResultFactory>();
  496. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  497. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  498. serviceCollection.AddSingleton(ServerConfigurationManager);
  499. serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  500. serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  501. serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  502. serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  503. serviceCollection.AddSingleton<IDisplayPreferencesRepository, SqliteDisplayPreferencesRepository>();
  504. serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  505. serviceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  506. serviceCollection.AddSingleton<IUserRepository, SqliteUserRepository>();
  507. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  508. serviceCollection.AddTransient(provider => new Lazy<IDtoService>(provider.GetRequiredService<IDtoService>));
  509. serviceCollection.AddSingleton<IUserManager, UserManager>();
  510. // TODO: Add StartupOptions.FFmpegPath to IConfiguration so this doesn't need to be constructed manually
  511. serviceCollection.AddSingleton<IMediaEncoder>(provider =>
  512. new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  513. provider.GetRequiredService<ILogger<MediaBrowser.MediaEncoding.Encoder.MediaEncoder>>(),
  514. provider.GetRequiredService<IServerConfigurationManager>(),
  515. provider.GetRequiredService<IFileSystem>(),
  516. provider.GetRequiredService<IProcessFactory>(),
  517. provider.GetRequiredService<ILocalizationManager>(),
  518. provider.GetRequiredService<ISubtitleEncoder>,
  519. provider.GetRequiredService<IConfiguration>(),
  520. StartupOptions.FFmpegPath));
  521. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  522. serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  523. serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  524. serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  525. serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  526. serviceCollection.AddSingleton<IMusicManager, MusicManager>();
  527. serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  528. serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  529. serviceCollection.AddSingleton<ServiceController>();
  530. serviceCollection.AddSingleton<IHttpListener, WebSocketSharpListener>();
  531. serviceCollection.AddSingleton<IHttpServer, HttpListenerHost>();
  532. serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  533. serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  534. serviceCollection.AddSingleton<IDeviceManager, DeviceManager>();
  535. serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  536. serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  537. serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
  538. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  539. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  540. serviceCollection.AddSingleton<IDtoService, DtoService>();
  541. serviceCollection.AddSingleton<IChannelManager, ChannelManager>();
  542. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  543. serviceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  544. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  545. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  546. serviceCollection.AddSingleton<LiveTvDtoService>();
  547. serviceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  548. serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  549. serviceCollection.AddSingleton<INotificationManager, NotificationManager>();
  550. serviceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  551. serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
  552. serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  553. serviceCollection.AddSingleton<IActivityRepository, ActivityRepository>();
  554. serviceCollection.AddSingleton<IActivityManager, ActivityManager>();
  555. serviceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  556. serviceCollection.AddSingleton<ISessionContext, SessionContext>();
  557. serviceCollection.AddSingleton<IAuthService, AuthService>();
  558. serviceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  559. serviceCollection.AddSingleton<IResourceFileManager, ResourceFileManager>();
  560. serviceCollection.AddSingleton<EncodingHelper>();
  561. serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  562. }
  563. /// <summary>
  564. /// Create services registered with the service container that need to be initialized at application startup.
  565. /// </summary>
  566. /// <returns>A task representing the service initialization operation.</returns>
  567. public async Task InitializeServices()
  568. {
  569. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  570. await localizationManager.LoadAll().ConfigureAwait(false);
  571. _mediaEncoder = Resolve<IMediaEncoder>();
  572. _sessionManager = Resolve<ISessionManager>();
  573. _httpServer = Resolve<IHttpServer>();
  574. _httpClient = Resolve<IHttpClient>();
  575. ((SqliteDisplayPreferencesRepository)Resolve<IDisplayPreferencesRepository>()).Initialize();
  576. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  577. ((SqliteUserRepository)Resolve<IUserRepository>()).Initialize();
  578. ((ActivityRepository)Resolve<IActivityRepository>()).Initialize();
  579. SetStaticProperties();
  580. var userManager = (UserManager)Resolve<IUserManager>();
  581. userManager.Initialize();
  582. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  583. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, userManager);
  584. FindParts();
  585. }
  586. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  587. {
  588. // Distinct these to prevent users from reporting problems that aren't actually problems
  589. var commandLineArgs = Environment
  590. .GetCommandLineArgs()
  591. .Distinct();
  592. // Get all 'JELLYFIN_' prefixed environment variables
  593. var allEnvVars = Environment.GetEnvironmentVariables();
  594. var jellyfinEnvVars = new Dictionary<object, object>();
  595. foreach (var key in allEnvVars.Keys)
  596. {
  597. if (key.ToString().StartsWith("JELLYFIN_", StringComparison.OrdinalIgnoreCase))
  598. {
  599. jellyfinEnvVars.Add(key, allEnvVars[key]);
  600. }
  601. }
  602. logger.LogInformation("Environment Variables: {EnvVars}", jellyfinEnvVars);
  603. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  604. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  605. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  606. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  607. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  608. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  609. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  610. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  611. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  612. }
  613. private X509Certificate2 GetCertificate(CertificateInfo info)
  614. {
  615. var certificateLocation = info?.Path;
  616. if (string.IsNullOrWhiteSpace(certificateLocation))
  617. {
  618. return null;
  619. }
  620. try
  621. {
  622. if (!File.Exists(certificateLocation))
  623. {
  624. return null;
  625. }
  626. // Don't use an empty string password
  627. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  628. var localCert = new X509Certificate2(certificateLocation, password);
  629. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  630. if (!localCert.HasPrivateKey)
  631. {
  632. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  633. return null;
  634. }
  635. return localCert;
  636. }
  637. catch (Exception ex)
  638. {
  639. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  640. return null;
  641. }
  642. }
  643. /// <summary>
  644. /// Dirty hacks.
  645. /// </summary>
  646. private void SetStaticProperties()
  647. {
  648. // For now there's no real way to inject these properly
  649. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  650. BaseItem.ConfigurationManager = ServerConfigurationManager;
  651. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  652. BaseItem.ProviderManager = Resolve<IProviderManager>();
  653. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  654. BaseItem.ItemRepository = Resolve<IItemRepository>();
  655. User.UserManager = Resolve<IUserManager>();
  656. BaseItem.FileSystem = FileSystemManager;
  657. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  658. BaseItem.ChannelManager = Resolve<IChannelManager>();
  659. Video.LiveTvManager = Resolve<ILiveTvManager>();
  660. Folder.UserViewManager = Resolve<IUserViewManager>();
  661. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  662. UserView.CollectionManager = Resolve<ICollectionManager>();
  663. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  664. CollectionFolder.XmlSerializer = XmlSerializer;
  665. CollectionFolder.JsonSerializer = JsonSerializer;
  666. CollectionFolder.ApplicationHost = this;
  667. AuthenticatedAttribute.AuthService = Resolve<IAuthService>();
  668. }
  669. private async void PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> args)
  670. {
  671. string dir = Path.Combine(ApplicationPaths.PluginsPath, args.Argument.name);
  672. var types = Directory.EnumerateFiles(dir, "*.dll", SearchOption.AllDirectories)
  673. .Select(Assembly.LoadFrom)
  674. .SelectMany(x => x.ExportedTypes)
  675. .Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface && !x.IsGenericType)
  676. .ToArray();
  677. int oldLen = _allConcreteTypes.Length;
  678. Array.Resize(ref _allConcreteTypes, oldLen + types.Length);
  679. types.CopyTo(_allConcreteTypes, oldLen);
  680. var plugins = types.Where(x => x.IsAssignableFrom(typeof(IPlugin)))
  681. .Select(CreateInstanceSafe)
  682. .Where(x => x != null)
  683. .Cast<IPlugin>()
  684. .Select(LoadPlugin)
  685. .Where(x => x != null)
  686. .ToArray();
  687. oldLen = _plugins.Length;
  688. Array.Resize(ref _plugins, oldLen + plugins.Length);
  689. plugins.CopyTo(_plugins, oldLen);
  690. var entries = types.Where(x => x.IsAssignableFrom(typeof(IServerEntryPoint)))
  691. .Select(CreateInstanceSafe)
  692. .Where(x => x != null)
  693. .Cast<IServerEntryPoint>()
  694. .ToList();
  695. await Task.WhenAll(StartEntryPoints(entries, true)).ConfigureAwait(false);
  696. await Task.WhenAll(StartEntryPoints(entries, false)).ConfigureAwait(false);
  697. }
  698. /// <summary>
  699. /// Finds plugin components and register them with the appropriate services.
  700. /// </summary>
  701. private void FindParts()
  702. {
  703. InstallationManager = ServiceProvider.GetService<IInstallationManager>();
  704. InstallationManager.PluginInstalled += PluginInstalled;
  705. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  706. {
  707. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  708. ConfigurationManager.SaveConfiguration();
  709. }
  710. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  711. _plugins = GetExports<IPlugin>()
  712. .Select(LoadPlugin)
  713. .Where(i => i != null)
  714. .ToArray();
  715. _httpServer.Init(GetExportTypes<IService>(), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  716. Resolve<ILibraryManager>().AddParts(
  717. GetExports<IResolverIgnoreRule>(),
  718. GetExports<IItemResolver>(),
  719. GetExports<IIntroProvider>(),
  720. GetExports<IBaseItemComparer>(),
  721. GetExports<ILibraryPostScanTask>());
  722. Resolve<IProviderManager>().AddParts(
  723. GetExports<IImageProvider>(),
  724. GetExports<IMetadataService>(),
  725. GetExports<IMetadataProvider>(),
  726. GetExports<IMetadataSaver>(),
  727. GetExports<IExternalId>());
  728. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  729. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  730. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  731. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  732. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  733. Resolve<IUserManager>().AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  734. Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>());
  735. }
  736. private IPlugin LoadPlugin(IPlugin plugin)
  737. {
  738. try
  739. {
  740. if (plugin is IPluginAssembly assemblyPlugin)
  741. {
  742. var assembly = plugin.GetType().Assembly;
  743. var assemblyName = assembly.GetName();
  744. var assemblyFilePath = assembly.Location;
  745. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  746. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  747. try
  748. {
  749. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  750. if (idAttributes.Length > 0)
  751. {
  752. var attribute = (GuidAttribute)idAttributes[0];
  753. var assemblyId = new Guid(attribute.Value);
  754. assemblyPlugin.SetId(assemblyId);
  755. }
  756. }
  757. catch (Exception ex)
  758. {
  759. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  760. }
  761. }
  762. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  763. {
  764. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  765. }
  766. }
  767. catch (Exception ex)
  768. {
  769. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  770. return null;
  771. }
  772. return plugin;
  773. }
  774. /// <summary>
  775. /// Discovers the types.
  776. /// </summary>
  777. protected void DiscoverTypes()
  778. {
  779. Logger.LogInformation("Loading assemblies");
  780. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  781. }
  782. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  783. {
  784. foreach (var ass in assemblies)
  785. {
  786. Type[] exportedTypes;
  787. try
  788. {
  789. exportedTypes = ass.GetExportedTypes();
  790. }
  791. catch (FileNotFoundException ex)
  792. {
  793. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  794. continue;
  795. }
  796. foreach (Type type in exportedTypes)
  797. {
  798. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  799. {
  800. yield return type;
  801. }
  802. }
  803. }
  804. }
  805. private CertificateInfo CertificateInfo { get; set; }
  806. public X509Certificate2 Certificate { get; private set; }
  807. private IEnumerable<string> GetUrlPrefixes()
  808. {
  809. var hosts = new[] { "+" };
  810. return hosts.SelectMany(i =>
  811. {
  812. var prefixes = new List<string>
  813. {
  814. "http://" + i + ":" + HttpPort + "/"
  815. };
  816. if (CertificateInfo != null)
  817. {
  818. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  819. }
  820. return prefixes;
  821. });
  822. }
  823. /// <summary>
  824. /// Called when [configuration updated].
  825. /// </summary>
  826. /// <param name="sender">The sender.</param>
  827. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  828. protected void OnConfigurationUpdated(object sender, EventArgs e)
  829. {
  830. var requiresRestart = false;
  831. // Don't do anything if these haven't been set yet
  832. if (HttpPort != 0 && HttpsPort != 0)
  833. {
  834. // Need to restart if ports have changed
  835. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  836. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  837. {
  838. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  839. {
  840. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  841. ServerConfigurationManager.SaveConfiguration();
  842. requiresRestart = true;
  843. }
  844. }
  845. }
  846. if (!_httpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  847. {
  848. requiresRestart = true;
  849. }
  850. var currentCertPath = CertificateInfo?.Path;
  851. var newCertPath = ServerConfigurationManager.Configuration.CertificatePath;
  852. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  853. {
  854. requiresRestart = true;
  855. }
  856. if (requiresRestart)
  857. {
  858. Logger.LogInformation("App needs to be restarted due to configuration change.");
  859. NotifyPendingRestart();
  860. }
  861. }
  862. /// <summary>
  863. /// Notifies that the kernel that a change has been made that requires a restart
  864. /// </summary>
  865. public void NotifyPendingRestart()
  866. {
  867. Logger.LogInformation("App needs to be restarted.");
  868. var changed = !HasPendingRestart;
  869. HasPendingRestart = true;
  870. if (changed)
  871. {
  872. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  873. }
  874. }
  875. /// <summary>
  876. /// Restarts this instance.
  877. /// </summary>
  878. public void Restart()
  879. {
  880. if (!CanSelfRestart)
  881. {
  882. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  883. }
  884. if (IsShuttingDown)
  885. {
  886. return;
  887. }
  888. IsShuttingDown = true;
  889. Task.Run(async () =>
  890. {
  891. try
  892. {
  893. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  894. }
  895. catch (Exception ex)
  896. {
  897. Logger.LogError(ex, "Error sending server restart notification");
  898. }
  899. Logger.LogInformation("Calling RestartInternal");
  900. RestartInternal();
  901. });
  902. }
  903. protected abstract void RestartInternal();
  904. /// <summary>
  905. /// Gets the composable part assemblies.
  906. /// </summary>
  907. /// <returns>IEnumerable{Assembly}.</returns>
  908. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  909. {
  910. if (Directory.Exists(ApplicationPaths.PluginsPath))
  911. {
  912. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  913. {
  914. Assembly plugAss;
  915. try
  916. {
  917. plugAss = Assembly.LoadFrom(file);
  918. }
  919. catch (FileLoadException ex)
  920. {
  921. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  922. continue;
  923. }
  924. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  925. yield return plugAss;
  926. }
  927. }
  928. // Include composable parts in the Api assembly
  929. yield return typeof(ApiEntryPoint).Assembly;
  930. // Include composable parts in the Dashboard assembly
  931. yield return typeof(DashboardService).Assembly;
  932. // Include composable parts in the Model assembly
  933. yield return typeof(SystemInfo).Assembly;
  934. // Include composable parts in the Common assembly
  935. yield return typeof(IApplicationHost).Assembly;
  936. // Include composable parts in the Controller assembly
  937. yield return typeof(IServerApplicationHost).Assembly;
  938. // Include composable parts in the Providers assembly
  939. yield return typeof(ProviderUtils).Assembly;
  940. // Include composable parts in the Photos assembly
  941. yield return typeof(PhotoProvider).Assembly;
  942. // Emby.Server implementations
  943. yield return typeof(InstallationManager).Assembly;
  944. // MediaEncoding
  945. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  946. // Dlna
  947. yield return typeof(DlnaEntryPoint).Assembly;
  948. // Local metadata
  949. yield return typeof(BoxSetXmlSaver).Assembly;
  950. // Notifications
  951. yield return typeof(NotificationManager).Assembly;
  952. // Xbmc
  953. yield return typeof(ArtistNfoProvider).Assembly;
  954. foreach (var i in GetAssembliesWithPartsInternal())
  955. {
  956. yield return i;
  957. }
  958. }
  959. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  960. /// <summary>
  961. /// Gets the system status.
  962. /// </summary>
  963. /// <param name="cancellationToken">The cancellation token.</param>
  964. /// <returns>SystemInfo.</returns>
  965. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  966. {
  967. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  968. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  969. return new SystemInfo
  970. {
  971. HasPendingRestart = HasPendingRestart,
  972. IsShuttingDown = IsShuttingDown,
  973. Version = ApplicationVersionString,
  974. WebSocketPortNumber = HttpPort,
  975. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  976. Id = SystemId,
  977. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  978. WebPath = ApplicationPaths.WebPath,
  979. LogPath = ApplicationPaths.LogDirectoryPath,
  980. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  981. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  982. CachePath = ApplicationPaths.CachePath,
  983. HttpServerPortNumber = HttpPort,
  984. SupportsHttps = SupportsHttps,
  985. HttpsPortNumber = HttpsPort,
  986. OperatingSystem = OperatingSystem.Id.ToString(),
  987. OperatingSystemDisplayName = OperatingSystem.Name,
  988. CanSelfRestart = CanSelfRestart,
  989. CanLaunchWebBrowser = CanLaunchWebBrowser,
  990. HasUpdateAvailable = HasUpdateAvailable,
  991. TranscodingTempPath = transcodingTempPath,
  992. ServerName = FriendlyName,
  993. LocalAddress = localAddress,
  994. SupportsLibraryMonitor = true,
  995. EncoderLocation = _mediaEncoder.EncoderLocation,
  996. SystemArchitecture = RuntimeInformation.OSArchitecture,
  997. SystemUpdateLevel = SystemUpdateLevel,
  998. PackageName = StartupOptions.PackageName
  999. };
  1000. }
  1001. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  1002. => NetworkManager.GetMacAddresses()
  1003. .Select(i => new WakeOnLanInfo(i))
  1004. .ToList();
  1005. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1006. {
  1007. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1008. return new PublicSystemInfo
  1009. {
  1010. Version = ApplicationVersionString,
  1011. ProductName = ApplicationProductName,
  1012. Id = SystemId,
  1013. OperatingSystem = OperatingSystem.Id.ToString(),
  1014. ServerName = FriendlyName,
  1015. LocalAddress = localAddress
  1016. };
  1017. }
  1018. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1019. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1020. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1021. {
  1022. try
  1023. {
  1024. // Return the first matched address, if found, or the first known local address
  1025. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1026. foreach (var address in addresses)
  1027. {
  1028. return GetLocalApiUrl(address);
  1029. }
  1030. return null;
  1031. }
  1032. catch (Exception ex)
  1033. {
  1034. Logger.LogError(ex, "Error getting local Ip address information");
  1035. }
  1036. return null;
  1037. }
  1038. /// <summary>
  1039. /// Removes the scope id from IPv6 addresses.
  1040. /// </summary>
  1041. /// <param name="address">The IPv6 address.</param>
  1042. /// <returns>The IPv6 address without the scope id.</returns>
  1043. private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
  1044. {
  1045. var index = address.IndexOf('%');
  1046. if (index == -1)
  1047. {
  1048. return address;
  1049. }
  1050. return address.Slice(0, index);
  1051. }
  1052. /// <inheritdoc />
  1053. public string GetLocalApiUrl(IPAddress ipAddress)
  1054. {
  1055. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1056. {
  1057. var str = RemoveScopeId(ipAddress.ToString());
  1058. Span<char> span = new char[str.Length + 2];
  1059. span[0] = '[';
  1060. str.CopyTo(span.Slice(1));
  1061. span[^1] = ']';
  1062. return GetLocalApiUrl(span);
  1063. }
  1064. return GetLocalApiUrl(ipAddress.ToString());
  1065. }
  1066. /// <inheritdoc />
  1067. public string GetLocalApiUrl(ReadOnlySpan<char> host)
  1068. {
  1069. var url = new StringBuilder(64);
  1070. url.Append(EnableHttps ? "https://" : "http://")
  1071. .Append(host)
  1072. .Append(':')
  1073. .Append(EnableHttps ? HttpsPort : HttpPort);
  1074. string baseUrl = ServerConfigurationManager.Configuration.BaseUrl;
  1075. if (baseUrl.Length != 0)
  1076. {
  1077. url.Append(baseUrl);
  1078. }
  1079. return url.ToString();
  1080. }
  1081. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1082. {
  1083. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1084. }
  1085. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1086. {
  1087. var addresses = ServerConfigurationManager
  1088. .Configuration
  1089. .LocalNetworkAddresses
  1090. .Select(NormalizeConfiguredLocalAddress)
  1091. .Where(i => i != null)
  1092. .ToList();
  1093. if (addresses.Count == 0)
  1094. {
  1095. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1096. }
  1097. var resultList = new List<IPAddress>();
  1098. foreach (var address in addresses)
  1099. {
  1100. if (!allowLoopback)
  1101. {
  1102. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1103. {
  1104. continue;
  1105. }
  1106. }
  1107. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1108. if (valid)
  1109. {
  1110. resultList.Add(address);
  1111. if (limit > 0 && resultList.Count >= limit)
  1112. {
  1113. return resultList;
  1114. }
  1115. }
  1116. }
  1117. return resultList;
  1118. }
  1119. public IPAddress NormalizeConfiguredLocalAddress(string address)
  1120. {
  1121. var index = address.Trim('/').IndexOf('/');
  1122. if (index != -1)
  1123. {
  1124. address = address.Substring(index + 1);
  1125. }
  1126. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1127. {
  1128. return result;
  1129. }
  1130. return null;
  1131. }
  1132. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1133. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1134. {
  1135. if (address.Equals(IPAddress.Loopback)
  1136. || address.Equals(IPAddress.IPv6Loopback))
  1137. {
  1138. return true;
  1139. }
  1140. var apiUrl = GetLocalApiUrl(address);
  1141. apiUrl += "/system/ping";
  1142. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1143. {
  1144. return cachedResult;
  1145. }
  1146. try
  1147. {
  1148. using (var response = await _httpClient.SendAsync(
  1149. new HttpRequestOptions
  1150. {
  1151. Url = apiUrl,
  1152. LogErrorResponseBody = false,
  1153. BufferContent = false,
  1154. CancellationToken = cancellationToken
  1155. }, HttpMethod.Post).ConfigureAwait(false))
  1156. {
  1157. using (var reader = new StreamReader(response.Content))
  1158. {
  1159. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1160. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1161. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1162. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1163. return valid;
  1164. }
  1165. }
  1166. }
  1167. catch (OperationCanceledException)
  1168. {
  1169. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1170. throw;
  1171. }
  1172. catch (Exception ex)
  1173. {
  1174. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1175. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1176. return false;
  1177. }
  1178. }
  1179. public string FriendlyName =>
  1180. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1181. ? Environment.MachineName
  1182. : ServerConfigurationManager.Configuration.ServerName;
  1183. /// <summary>
  1184. /// Shuts down.
  1185. /// </summary>
  1186. public async Task Shutdown()
  1187. {
  1188. if (IsShuttingDown)
  1189. {
  1190. return;
  1191. }
  1192. IsShuttingDown = true;
  1193. try
  1194. {
  1195. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1196. }
  1197. catch (Exception ex)
  1198. {
  1199. Logger.LogError(ex, "Error sending server shutdown notification");
  1200. }
  1201. ShutdownInternal();
  1202. }
  1203. protected abstract void ShutdownInternal();
  1204. public event EventHandler HasUpdateAvailableChanged;
  1205. private bool _hasUpdateAvailable;
  1206. public bool HasUpdateAvailable
  1207. {
  1208. get => _hasUpdateAvailable;
  1209. set
  1210. {
  1211. var fireEvent = value && !_hasUpdateAvailable;
  1212. _hasUpdateAvailable = value;
  1213. if (fireEvent)
  1214. {
  1215. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1216. }
  1217. }
  1218. }
  1219. /// <summary>
  1220. /// Removes the plugin.
  1221. /// </summary>
  1222. /// <param name="plugin">The plugin.</param>
  1223. public void RemovePlugin(IPlugin plugin)
  1224. {
  1225. var list = _plugins.ToList();
  1226. list.Remove(plugin);
  1227. _plugins = list.ToArray();
  1228. }
  1229. public virtual void LaunchUrl(string url)
  1230. {
  1231. if (!CanLaunchWebBrowser)
  1232. {
  1233. throw new NotSupportedException();
  1234. }
  1235. var process = Resolve<IProcessFactory>().Create(new ProcessOptions
  1236. {
  1237. FileName = url,
  1238. EnableRaisingEvents = true,
  1239. UseShellExecute = true,
  1240. ErrorDialog = false
  1241. });
  1242. process.Exited += ProcessExited;
  1243. try
  1244. {
  1245. process.Start();
  1246. }
  1247. catch (Exception ex)
  1248. {
  1249. Logger.LogError(ex, "Error launching url: {url}", url);
  1250. throw;
  1251. }
  1252. }
  1253. private static void ProcessExited(object sender, EventArgs e)
  1254. {
  1255. ((IProcess)sender).Dispose();
  1256. }
  1257. public virtual void EnableLoopback(string appName)
  1258. {
  1259. }
  1260. private bool _disposed = false;
  1261. /// <summary>
  1262. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1263. /// </summary>
  1264. public void Dispose()
  1265. {
  1266. Dispose(true);
  1267. GC.SuppressFinalize(this);
  1268. }
  1269. /// <summary>
  1270. /// Releases unmanaged and - optionally - managed resources.
  1271. /// </summary>
  1272. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1273. protected virtual void Dispose(bool dispose)
  1274. {
  1275. if (_disposed)
  1276. {
  1277. return;
  1278. }
  1279. if (dispose)
  1280. {
  1281. var type = GetType();
  1282. Logger.LogInformation("Disposing {Type}", type.Name);
  1283. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1284. _disposableParts.Clear();
  1285. foreach (var part in parts)
  1286. {
  1287. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1288. try
  1289. {
  1290. part.Dispose();
  1291. }
  1292. catch (Exception ex)
  1293. {
  1294. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1295. }
  1296. }
  1297. _userRepository?.Dispose();
  1298. }
  1299. _userRepository = null;
  1300. _disposed = true;
  1301. }
  1302. }
  1303. internal class CertificateInfo
  1304. {
  1305. public string Path { get; set; }
  1306. public string Password { get; set; }
  1307. }
  1308. }