ApplicationHost.cs 68 KB

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