ApplicationHost.cs 61 KB

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