ApplicationHost.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  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: Remove support for injecting ILogger completely
  481. serviceCollection.AddSingleton((provider) =>
  482. {
  483. Logger.LogWarning("Injecting ILogger directly is deprecated and should be replaced with ILogger<T>");
  484. return Logger;
  485. });
  486. serviceCollection.AddSingleton(FileSystemManager);
  487. serviceCollection.AddSingleton<TvdbClientManager>();
  488. serviceCollection.AddSingleton<IHttpClient, HttpClientManager.HttpClientManager>();
  489. serviceCollection.AddSingleton(NetworkManager);
  490. serviceCollection.AddSingleton<IIsoManager, IsoManager>();
  491. serviceCollection.AddSingleton<ITaskManager, TaskManager>();
  492. serviceCollection.AddSingleton(XmlSerializer);
  493. serviceCollection.AddSingleton<IProcessFactory, ProcessFactory>();
  494. serviceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  495. serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  496. serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  497. serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  498. serviceCollection.AddSingleton<IZipClient, ZipClient>();
  499. serviceCollection.AddSingleton<IHttpResultFactory, HttpResultFactory>();
  500. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  501. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  502. serviceCollection.AddSingleton(ServerConfigurationManager);
  503. serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  504. serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  505. serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  506. serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  507. serviceCollection.AddSingleton<IDisplayPreferencesRepository, SqliteDisplayPreferencesRepository>();
  508. serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  509. serviceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  510. serviceCollection.AddSingleton<IUserRepository, SqliteUserRepository>();
  511. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  512. serviceCollection.AddTransient(provider => new Lazy<IDtoService>(provider.GetRequiredService<IDtoService>));
  513. serviceCollection.AddSingleton<IUserManager, UserManager>();
  514. // TODO: Add StartupOptions.FFmpegPath to IConfiguration so this doesn't need to be constructed manually
  515. serviceCollection.AddSingleton<IMediaEncoder>(provider =>
  516. new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  517. provider.GetRequiredService<ILogger<MediaBrowser.MediaEncoding.Encoder.MediaEncoder>>(),
  518. provider.GetRequiredService<IServerConfigurationManager>(),
  519. provider.GetRequiredService<IFileSystem>(),
  520. provider.GetRequiredService<IProcessFactory>(),
  521. provider.GetRequiredService<ILocalizationManager>(),
  522. provider.GetRequiredService<ISubtitleEncoder>,
  523. provider.GetRequiredService<IConfiguration>(),
  524. StartupOptions.FFmpegPath));
  525. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  526. serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  527. serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  528. serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  529. serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  530. serviceCollection.AddSingleton<IMusicManager, MusicManager>();
  531. serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  532. serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  533. serviceCollection.AddSingleton<ServiceController>();
  534. serviceCollection.AddSingleton<IHttpListener, WebSocketSharpListener>();
  535. serviceCollection.AddSingleton<IHttpServer, HttpListenerHost>();
  536. serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  537. serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  538. serviceCollection.AddSingleton<IDeviceManager, DeviceManager>();
  539. serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  540. serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  541. serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
  542. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  543. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  544. serviceCollection.AddSingleton<IDtoService, DtoService>();
  545. serviceCollection.AddSingleton<IChannelManager, ChannelManager>();
  546. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  547. serviceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  548. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  549. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  550. serviceCollection.AddSingleton<LiveTvDtoService>();
  551. serviceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  552. serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  553. serviceCollection.AddSingleton<INotificationManager, NotificationManager>();
  554. serviceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  555. serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
  556. serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  557. serviceCollection.AddSingleton<IActivityRepository, ActivityRepository>();
  558. serviceCollection.AddSingleton<IActivityManager, ActivityManager>();
  559. serviceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  560. serviceCollection.AddSingleton<ISessionContext, SessionContext>();
  561. serviceCollection.AddSingleton<IAuthService, AuthService>();
  562. serviceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  563. serviceCollection.AddSingleton<IResourceFileManager, ResourceFileManager>();
  564. serviceCollection.AddSingleton<EncodingHelper>();
  565. serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  566. }
  567. /// <summary>
  568. /// Create services registered with the service container that need to be initialized at application startup.
  569. /// </summary>
  570. /// <returns>A task representing the service initialization operation.</returns>
  571. public async Task InitializeServices()
  572. {
  573. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  574. await localizationManager.LoadAll().ConfigureAwait(false);
  575. _mediaEncoder = Resolve<IMediaEncoder>();
  576. _sessionManager = Resolve<ISessionManager>();
  577. _httpServer = Resolve<IHttpServer>();
  578. _httpClient = Resolve<IHttpClient>();
  579. ((SqliteDisplayPreferencesRepository)Resolve<IDisplayPreferencesRepository>()).Initialize();
  580. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  581. ((SqliteUserRepository)Resolve<IUserRepository>()).Initialize();
  582. ((ActivityRepository)Resolve<IActivityRepository>()).Initialize();
  583. SetStaticProperties();
  584. var userManager = (UserManager)Resolve<IUserManager>();
  585. userManager.Initialize();
  586. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  587. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, userManager);
  588. FindParts();
  589. }
  590. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  591. {
  592. // Distinct these to prevent users from reporting problems that aren't actually problems
  593. var commandLineArgs = Environment
  594. .GetCommandLineArgs()
  595. .Distinct();
  596. // Get all 'JELLYFIN_' prefixed environment variables
  597. var allEnvVars = Environment.GetEnvironmentVariables();
  598. var jellyfinEnvVars = new Dictionary<object, object>();
  599. foreach (var key in allEnvVars.Keys)
  600. {
  601. if (key.ToString().StartsWith("JELLYFIN_", StringComparison.OrdinalIgnoreCase))
  602. {
  603. jellyfinEnvVars.Add(key, allEnvVars[key]);
  604. }
  605. }
  606. logger.LogInformation("Environment Variables: {EnvVars}", jellyfinEnvVars);
  607. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  608. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  609. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  610. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  611. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  612. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  613. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  614. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  615. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  616. }
  617. private X509Certificate2 GetCertificate(CertificateInfo info)
  618. {
  619. var certificateLocation = info?.Path;
  620. if (string.IsNullOrWhiteSpace(certificateLocation))
  621. {
  622. return null;
  623. }
  624. try
  625. {
  626. if (!File.Exists(certificateLocation))
  627. {
  628. return null;
  629. }
  630. // Don't use an empty string password
  631. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  632. var localCert = new X509Certificate2(certificateLocation, password);
  633. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  634. if (!localCert.HasPrivateKey)
  635. {
  636. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  637. return null;
  638. }
  639. return localCert;
  640. }
  641. catch (Exception ex)
  642. {
  643. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  644. return null;
  645. }
  646. }
  647. /// <summary>
  648. /// Dirty hacks.
  649. /// </summary>
  650. private void SetStaticProperties()
  651. {
  652. // For now there's no real way to inject these properly
  653. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  654. BaseItem.ConfigurationManager = ServerConfigurationManager;
  655. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  656. BaseItem.ProviderManager = Resolve<IProviderManager>();
  657. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  658. BaseItem.ItemRepository = Resolve<IItemRepository>();
  659. User.UserManager = Resolve<IUserManager>();
  660. BaseItem.FileSystem = FileSystemManager;
  661. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  662. BaseItem.ChannelManager = Resolve<IChannelManager>();
  663. Video.LiveTvManager = Resolve<ILiveTvManager>();
  664. Folder.UserViewManager = Resolve<IUserViewManager>();
  665. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  666. UserView.CollectionManager = Resolve<ICollectionManager>();
  667. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  668. CollectionFolder.XmlSerializer = XmlSerializer;
  669. CollectionFolder.JsonSerializer = JsonSerializer;
  670. CollectionFolder.ApplicationHost = this;
  671. AuthenticatedAttribute.AuthService = Resolve<IAuthService>();
  672. }
  673. private async void PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> args)
  674. {
  675. string dir = Path.Combine(ApplicationPaths.PluginsPath, args.Argument.name);
  676. var types = Directory.EnumerateFiles(dir, "*.dll", SearchOption.AllDirectories)
  677. .Select(Assembly.LoadFrom)
  678. .SelectMany(x => x.ExportedTypes)
  679. .Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface && !x.IsGenericType)
  680. .ToArray();
  681. int oldLen = _allConcreteTypes.Length;
  682. Array.Resize(ref _allConcreteTypes, oldLen + types.Length);
  683. types.CopyTo(_allConcreteTypes, oldLen);
  684. var plugins = types.Where(x => x.IsAssignableFrom(typeof(IPlugin)))
  685. .Select(CreateInstanceSafe)
  686. .Where(x => x != null)
  687. .Cast<IPlugin>()
  688. .Select(LoadPlugin)
  689. .Where(x => x != null)
  690. .ToArray();
  691. oldLen = _plugins.Length;
  692. Array.Resize(ref _plugins, oldLen + plugins.Length);
  693. plugins.CopyTo(_plugins, oldLen);
  694. var entries = types.Where(x => x.IsAssignableFrom(typeof(IServerEntryPoint)))
  695. .Select(CreateInstanceSafe)
  696. .Where(x => x != null)
  697. .Cast<IServerEntryPoint>()
  698. .ToList();
  699. await Task.WhenAll(StartEntryPoints(entries, true)).ConfigureAwait(false);
  700. await Task.WhenAll(StartEntryPoints(entries, false)).ConfigureAwait(false);
  701. }
  702. /// <summary>
  703. /// Finds plugin components and register them with the appropriate services.
  704. /// </summary>
  705. private void FindParts()
  706. {
  707. InstallationManager = ServiceProvider.GetService<IInstallationManager>();
  708. InstallationManager.PluginInstalled += PluginInstalled;
  709. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  710. {
  711. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  712. ConfigurationManager.SaveConfiguration();
  713. }
  714. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  715. _plugins = GetExports<IPlugin>()
  716. .Select(LoadPlugin)
  717. .Where(i => i != null)
  718. .ToArray();
  719. _httpServer.Init(GetExportTypes<IService>(), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  720. Resolve<ILibraryManager>().AddParts(
  721. GetExports<IResolverIgnoreRule>(),
  722. GetExports<IItemResolver>(),
  723. GetExports<IIntroProvider>(),
  724. GetExports<IBaseItemComparer>(),
  725. GetExports<ILibraryPostScanTask>());
  726. Resolve<IProviderManager>().AddParts(
  727. GetExports<IImageProvider>(),
  728. GetExports<IMetadataService>(),
  729. GetExports<IMetadataProvider>(),
  730. GetExports<IMetadataSaver>(),
  731. GetExports<IExternalId>());
  732. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  733. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  734. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  735. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  736. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  737. Resolve<IUserManager>().AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  738. Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>());
  739. }
  740. private IPlugin LoadPlugin(IPlugin plugin)
  741. {
  742. try
  743. {
  744. if (plugin is IPluginAssembly assemblyPlugin)
  745. {
  746. var assembly = plugin.GetType().Assembly;
  747. var assemblyName = assembly.GetName();
  748. var assemblyFilePath = assembly.Location;
  749. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  750. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  751. try
  752. {
  753. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  754. if (idAttributes.Length > 0)
  755. {
  756. var attribute = (GuidAttribute)idAttributes[0];
  757. var assemblyId = new Guid(attribute.Value);
  758. assemblyPlugin.SetId(assemblyId);
  759. }
  760. }
  761. catch (Exception ex)
  762. {
  763. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  764. }
  765. }
  766. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  767. {
  768. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  769. }
  770. }
  771. catch (Exception ex)
  772. {
  773. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  774. return null;
  775. }
  776. return plugin;
  777. }
  778. /// <summary>
  779. /// Discovers the types.
  780. /// </summary>
  781. protected void DiscoverTypes()
  782. {
  783. Logger.LogInformation("Loading assemblies");
  784. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  785. }
  786. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  787. {
  788. foreach (var ass in assemblies)
  789. {
  790. Type[] exportedTypes;
  791. try
  792. {
  793. exportedTypes = ass.GetExportedTypes();
  794. }
  795. catch (FileNotFoundException ex)
  796. {
  797. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  798. continue;
  799. }
  800. foreach (Type type in exportedTypes)
  801. {
  802. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  803. {
  804. yield return type;
  805. }
  806. }
  807. }
  808. }
  809. private CertificateInfo CertificateInfo { get; set; }
  810. public X509Certificate2 Certificate { get; private set; }
  811. private IEnumerable<string> GetUrlPrefixes()
  812. {
  813. var hosts = new[] { "+" };
  814. return hosts.SelectMany(i =>
  815. {
  816. var prefixes = new List<string>
  817. {
  818. "http://" + i + ":" + HttpPort + "/"
  819. };
  820. if (CertificateInfo != null)
  821. {
  822. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  823. }
  824. return prefixes;
  825. });
  826. }
  827. /// <summary>
  828. /// Called when [configuration updated].
  829. /// </summary>
  830. /// <param name="sender">The sender.</param>
  831. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  832. protected void OnConfigurationUpdated(object sender, EventArgs e)
  833. {
  834. var requiresRestart = false;
  835. // Don't do anything if these haven't been set yet
  836. if (HttpPort != 0 && HttpsPort != 0)
  837. {
  838. // Need to restart if ports have changed
  839. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  840. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  841. {
  842. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  843. {
  844. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  845. ServerConfigurationManager.SaveConfiguration();
  846. requiresRestart = true;
  847. }
  848. }
  849. }
  850. if (!_httpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  851. {
  852. requiresRestart = true;
  853. }
  854. var currentCertPath = CertificateInfo?.Path;
  855. var newCertPath = ServerConfigurationManager.Configuration.CertificatePath;
  856. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  857. {
  858. requiresRestart = true;
  859. }
  860. if (requiresRestart)
  861. {
  862. Logger.LogInformation("App needs to be restarted due to configuration change.");
  863. NotifyPendingRestart();
  864. }
  865. }
  866. /// <summary>
  867. /// Notifies that the kernel that a change has been made that requires a restart
  868. /// </summary>
  869. public void NotifyPendingRestart()
  870. {
  871. Logger.LogInformation("App needs to be restarted.");
  872. var changed = !HasPendingRestart;
  873. HasPendingRestart = true;
  874. if (changed)
  875. {
  876. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  877. }
  878. }
  879. /// <summary>
  880. /// Restarts this instance.
  881. /// </summary>
  882. public void Restart()
  883. {
  884. if (!CanSelfRestart)
  885. {
  886. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  887. }
  888. if (IsShuttingDown)
  889. {
  890. return;
  891. }
  892. IsShuttingDown = true;
  893. Task.Run(async () =>
  894. {
  895. try
  896. {
  897. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  898. }
  899. catch (Exception ex)
  900. {
  901. Logger.LogError(ex, "Error sending server restart notification");
  902. }
  903. Logger.LogInformation("Calling RestartInternal");
  904. RestartInternal();
  905. });
  906. }
  907. protected abstract void RestartInternal();
  908. /// <summary>
  909. /// Gets the composable part assemblies.
  910. /// </summary>
  911. /// <returns>IEnumerable{Assembly}.</returns>
  912. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  913. {
  914. if (Directory.Exists(ApplicationPaths.PluginsPath))
  915. {
  916. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  917. {
  918. Assembly plugAss;
  919. try
  920. {
  921. plugAss = Assembly.LoadFrom(file);
  922. }
  923. catch (FileLoadException ex)
  924. {
  925. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  926. continue;
  927. }
  928. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  929. yield return plugAss;
  930. }
  931. }
  932. // Include composable parts in the Api assembly
  933. yield return typeof(ApiEntryPoint).Assembly;
  934. // Include composable parts in the Dashboard assembly
  935. yield return typeof(DashboardService).Assembly;
  936. // Include composable parts in the Model assembly
  937. yield return typeof(SystemInfo).Assembly;
  938. // Include composable parts in the Common assembly
  939. yield return typeof(IApplicationHost).Assembly;
  940. // Include composable parts in the Controller assembly
  941. yield return typeof(IServerApplicationHost).Assembly;
  942. // Include composable parts in the Providers assembly
  943. yield return typeof(ProviderUtils).Assembly;
  944. // Include composable parts in the Photos assembly
  945. yield return typeof(PhotoProvider).Assembly;
  946. // Emby.Server implementations
  947. yield return typeof(InstallationManager).Assembly;
  948. // MediaEncoding
  949. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  950. // Dlna
  951. yield return typeof(DlnaEntryPoint).Assembly;
  952. // Local metadata
  953. yield return typeof(BoxSetXmlSaver).Assembly;
  954. // Notifications
  955. yield return typeof(NotificationManager).Assembly;
  956. // Xbmc
  957. yield return typeof(ArtistNfoProvider).Assembly;
  958. foreach (var i in GetAssembliesWithPartsInternal())
  959. {
  960. yield return i;
  961. }
  962. }
  963. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  964. /// <summary>
  965. /// Gets the system status.
  966. /// </summary>
  967. /// <param name="cancellationToken">The cancellation token.</param>
  968. /// <returns>SystemInfo.</returns>
  969. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  970. {
  971. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  972. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  973. return new SystemInfo
  974. {
  975. HasPendingRestart = HasPendingRestart,
  976. IsShuttingDown = IsShuttingDown,
  977. Version = ApplicationVersionString,
  978. WebSocketPortNumber = HttpPort,
  979. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  980. Id = SystemId,
  981. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  982. WebPath = ApplicationPaths.WebPath,
  983. LogPath = ApplicationPaths.LogDirectoryPath,
  984. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  985. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  986. CachePath = ApplicationPaths.CachePath,
  987. HttpServerPortNumber = HttpPort,
  988. SupportsHttps = SupportsHttps,
  989. HttpsPortNumber = HttpsPort,
  990. OperatingSystem = OperatingSystem.Id.ToString(),
  991. OperatingSystemDisplayName = OperatingSystem.Name,
  992. CanSelfRestart = CanSelfRestart,
  993. CanLaunchWebBrowser = CanLaunchWebBrowser,
  994. HasUpdateAvailable = HasUpdateAvailable,
  995. TranscodingTempPath = transcodingTempPath,
  996. ServerName = FriendlyName,
  997. LocalAddress = localAddress,
  998. SupportsLibraryMonitor = true,
  999. EncoderLocation = _mediaEncoder.EncoderLocation,
  1000. SystemArchitecture = RuntimeInformation.OSArchitecture,
  1001. SystemUpdateLevel = SystemUpdateLevel,
  1002. PackageName = StartupOptions.PackageName
  1003. };
  1004. }
  1005. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  1006. => NetworkManager.GetMacAddresses()
  1007. .Select(i => new WakeOnLanInfo(i))
  1008. .ToList();
  1009. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1010. {
  1011. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1012. return new PublicSystemInfo
  1013. {
  1014. Version = ApplicationVersionString,
  1015. ProductName = ApplicationProductName,
  1016. Id = SystemId,
  1017. OperatingSystem = OperatingSystem.Id.ToString(),
  1018. ServerName = FriendlyName,
  1019. LocalAddress = localAddress
  1020. };
  1021. }
  1022. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1023. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1024. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1025. {
  1026. try
  1027. {
  1028. // Return the first matched address, if found, or the first known local address
  1029. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1030. foreach (var address in addresses)
  1031. {
  1032. return GetLocalApiUrl(address);
  1033. }
  1034. return null;
  1035. }
  1036. catch (Exception ex)
  1037. {
  1038. Logger.LogError(ex, "Error getting local Ip address information");
  1039. }
  1040. return null;
  1041. }
  1042. /// <summary>
  1043. /// Removes the scope id from IPv6 addresses.
  1044. /// </summary>
  1045. /// <param name="address">The IPv6 address.</param>
  1046. /// <returns>The IPv6 address without the scope id.</returns>
  1047. private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
  1048. {
  1049. var index = address.IndexOf('%');
  1050. if (index == -1)
  1051. {
  1052. return address;
  1053. }
  1054. return address.Slice(0, index);
  1055. }
  1056. /// <inheritdoc />
  1057. public string GetLocalApiUrl(IPAddress ipAddress)
  1058. {
  1059. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1060. {
  1061. var str = RemoveScopeId(ipAddress.ToString());
  1062. Span<char> span = new char[str.Length + 2];
  1063. span[0] = '[';
  1064. str.CopyTo(span.Slice(1));
  1065. span[^1] = ']';
  1066. return GetLocalApiUrl(span);
  1067. }
  1068. return GetLocalApiUrl(ipAddress.ToString());
  1069. }
  1070. /// <inheritdoc />
  1071. public string GetLocalApiUrl(ReadOnlySpan<char> host)
  1072. {
  1073. var url = new StringBuilder(64);
  1074. url.Append(EnableHttps ? "https://" : "http://")
  1075. .Append(host)
  1076. .Append(':')
  1077. .Append(EnableHttps ? HttpsPort : HttpPort);
  1078. string baseUrl = ServerConfigurationManager.Configuration.BaseUrl;
  1079. if (baseUrl.Length != 0)
  1080. {
  1081. url.Append(baseUrl);
  1082. }
  1083. return url.ToString();
  1084. }
  1085. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1086. {
  1087. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1088. }
  1089. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1090. {
  1091. var addresses = ServerConfigurationManager
  1092. .Configuration
  1093. .LocalNetworkAddresses
  1094. .Select(NormalizeConfiguredLocalAddress)
  1095. .Where(i => i != null)
  1096. .ToList();
  1097. if (addresses.Count == 0)
  1098. {
  1099. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1100. }
  1101. var resultList = new List<IPAddress>();
  1102. foreach (var address in addresses)
  1103. {
  1104. if (!allowLoopback)
  1105. {
  1106. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1107. {
  1108. continue;
  1109. }
  1110. }
  1111. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1112. if (valid)
  1113. {
  1114. resultList.Add(address);
  1115. if (limit > 0 && resultList.Count >= limit)
  1116. {
  1117. return resultList;
  1118. }
  1119. }
  1120. }
  1121. return resultList;
  1122. }
  1123. public IPAddress NormalizeConfiguredLocalAddress(string address)
  1124. {
  1125. var index = address.Trim('/').IndexOf('/');
  1126. if (index != -1)
  1127. {
  1128. address = address.Substring(index + 1);
  1129. }
  1130. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1131. {
  1132. return result;
  1133. }
  1134. return null;
  1135. }
  1136. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1137. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1138. {
  1139. if (address.Equals(IPAddress.Loopback)
  1140. || address.Equals(IPAddress.IPv6Loopback))
  1141. {
  1142. return true;
  1143. }
  1144. var apiUrl = GetLocalApiUrl(address);
  1145. apiUrl += "/system/ping";
  1146. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1147. {
  1148. return cachedResult;
  1149. }
  1150. try
  1151. {
  1152. using (var response = await _httpClient.SendAsync(
  1153. new HttpRequestOptions
  1154. {
  1155. Url = apiUrl,
  1156. LogErrorResponseBody = false,
  1157. BufferContent = false,
  1158. CancellationToken = cancellationToken
  1159. }, HttpMethod.Post).ConfigureAwait(false))
  1160. {
  1161. using (var reader = new StreamReader(response.Content))
  1162. {
  1163. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1164. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1165. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1166. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1167. return valid;
  1168. }
  1169. }
  1170. }
  1171. catch (OperationCanceledException)
  1172. {
  1173. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1174. throw;
  1175. }
  1176. catch (Exception ex)
  1177. {
  1178. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1179. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1180. return false;
  1181. }
  1182. }
  1183. public string FriendlyName =>
  1184. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1185. ? Environment.MachineName
  1186. : ServerConfigurationManager.Configuration.ServerName;
  1187. /// <summary>
  1188. /// Shuts down.
  1189. /// </summary>
  1190. public async Task Shutdown()
  1191. {
  1192. if (IsShuttingDown)
  1193. {
  1194. return;
  1195. }
  1196. IsShuttingDown = true;
  1197. try
  1198. {
  1199. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1200. }
  1201. catch (Exception ex)
  1202. {
  1203. Logger.LogError(ex, "Error sending server shutdown notification");
  1204. }
  1205. ShutdownInternal();
  1206. }
  1207. protected abstract void ShutdownInternal();
  1208. public event EventHandler HasUpdateAvailableChanged;
  1209. private bool _hasUpdateAvailable;
  1210. public bool HasUpdateAvailable
  1211. {
  1212. get => _hasUpdateAvailable;
  1213. set
  1214. {
  1215. var fireEvent = value && !_hasUpdateAvailable;
  1216. _hasUpdateAvailable = value;
  1217. if (fireEvent)
  1218. {
  1219. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1220. }
  1221. }
  1222. }
  1223. /// <summary>
  1224. /// Removes the plugin.
  1225. /// </summary>
  1226. /// <param name="plugin">The plugin.</param>
  1227. public void RemovePlugin(IPlugin plugin)
  1228. {
  1229. var list = _plugins.ToList();
  1230. list.Remove(plugin);
  1231. _plugins = list.ToArray();
  1232. }
  1233. public virtual void LaunchUrl(string url)
  1234. {
  1235. if (!CanLaunchWebBrowser)
  1236. {
  1237. throw new NotSupportedException();
  1238. }
  1239. var process = Resolve<IProcessFactory>().Create(new ProcessOptions
  1240. {
  1241. FileName = url,
  1242. EnableRaisingEvents = true,
  1243. UseShellExecute = true,
  1244. ErrorDialog = false
  1245. });
  1246. process.Exited += ProcessExited;
  1247. try
  1248. {
  1249. process.Start();
  1250. }
  1251. catch (Exception ex)
  1252. {
  1253. Logger.LogError(ex, "Error launching url: {url}", url);
  1254. throw;
  1255. }
  1256. }
  1257. private static void ProcessExited(object sender, EventArgs e)
  1258. {
  1259. ((IProcess)sender).Dispose();
  1260. }
  1261. public virtual void EnableLoopback(string appName)
  1262. {
  1263. }
  1264. private bool _disposed = false;
  1265. /// <summary>
  1266. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1267. /// </summary>
  1268. public void Dispose()
  1269. {
  1270. Dispose(true);
  1271. GC.SuppressFinalize(this);
  1272. }
  1273. /// <summary>
  1274. /// Releases unmanaged and - optionally - managed resources.
  1275. /// </summary>
  1276. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1277. protected virtual void Dispose(bool dispose)
  1278. {
  1279. if (_disposed)
  1280. {
  1281. return;
  1282. }
  1283. if (dispose)
  1284. {
  1285. var type = GetType();
  1286. Logger.LogInformation("Disposing {Type}", type.Name);
  1287. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1288. _disposableParts.Clear();
  1289. foreach (var part in parts)
  1290. {
  1291. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1292. try
  1293. {
  1294. part.Dispose();
  1295. }
  1296. catch (Exception ex)
  1297. {
  1298. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1299. }
  1300. }
  1301. _userRepository?.Dispose();
  1302. }
  1303. _userRepository = null;
  1304. _disposed = true;
  1305. }
  1306. }
  1307. internal class CertificateInfo
  1308. {
  1309. public string Path { get; set; }
  1310. public string Password { get; set; }
  1311. }
  1312. }