ApplicationHost.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. using MediaBrowser.Api;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Configuration;
  4. using MediaBrowser.Common.Constants;
  5. using MediaBrowser.Common.Extensions;
  6. using MediaBrowser.Common.Implementations;
  7. using MediaBrowser.Common.Implementations.ScheduledTasks;
  8. using MediaBrowser.Common.IO;
  9. using MediaBrowser.Common.MediaInfo;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Drawing;
  14. using MediaBrowser.Controller.Dto;
  15. using MediaBrowser.Controller.Entities;
  16. using MediaBrowser.Controller.IO;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.LiveTv;
  19. using MediaBrowser.Controller.Localization;
  20. using MediaBrowser.Controller.MediaInfo;
  21. using MediaBrowser.Controller.Notifications;
  22. using MediaBrowser.Controller.Persistence;
  23. using MediaBrowser.Controller.Plugins;
  24. using MediaBrowser.Controller.Providers;
  25. using MediaBrowser.Controller.Resolvers;
  26. using MediaBrowser.Controller.Session;
  27. using MediaBrowser.Controller.Sorting;
  28. using MediaBrowser.Model.Logging;
  29. using MediaBrowser.Model.MediaInfo;
  30. using MediaBrowser.Model.System;
  31. using MediaBrowser.Model.Updates;
  32. using MediaBrowser.Providers;
  33. using MediaBrowser.Server.Implementations;
  34. using MediaBrowser.Server.Implementations.BdInfo;
  35. using MediaBrowser.Server.Implementations.Configuration;
  36. using MediaBrowser.Server.Implementations.Drawing;
  37. using MediaBrowser.Server.Implementations.Dto;
  38. using MediaBrowser.Server.Implementations.EntryPoints;
  39. using MediaBrowser.Server.Implementations.HttpServer;
  40. using MediaBrowser.Server.Implementations.IO;
  41. using MediaBrowser.Server.Implementations.Library;
  42. using MediaBrowser.Server.Implementations.LiveTv;
  43. using MediaBrowser.Server.Implementations.Localization;
  44. using MediaBrowser.Server.Implementations.MediaEncoder;
  45. using MediaBrowser.Server.Implementations.Persistence;
  46. using MediaBrowser.Server.Implementations.Providers;
  47. using MediaBrowser.Server.Implementations.ServerManager;
  48. using MediaBrowser.Server.Implementations.Session;
  49. using MediaBrowser.Server.Implementations.WebSocket;
  50. using MediaBrowser.ServerApplication.FFMpeg;
  51. using MediaBrowser.ServerApplication.IO;
  52. using MediaBrowser.ServerApplication.Native;
  53. using MediaBrowser.ServerApplication.Networking;
  54. using MediaBrowser.WebDashboard.Api;
  55. using System;
  56. using System.Collections.Generic;
  57. using System.IO;
  58. using System.Linq;
  59. using System.Net.Http;
  60. using System.Reflection;
  61. using System.Threading;
  62. using System.Threading.Tasks;
  63. namespace MediaBrowser.ServerApplication
  64. {
  65. /// <summary>
  66. /// Class CompositionRoot
  67. /// </summary>
  68. public class ApplicationHost : BaseApplicationHost<ServerApplicationPaths>, IServerApplicationHost
  69. {
  70. /// <summary>
  71. /// Gets the server kernel.
  72. /// </summary>
  73. /// <value>The server kernel.</value>
  74. protected Kernel ServerKernel { get; set; }
  75. /// <summary>
  76. /// Gets the server configuration manager.
  77. /// </summary>
  78. /// <value>The server configuration manager.</value>
  79. public IServerConfigurationManager ServerConfigurationManager
  80. {
  81. get { return (IServerConfigurationManager)ConfigurationManager; }
  82. }
  83. /// <summary>
  84. /// Gets the name of the web application that can be used for url building.
  85. /// All api urls will be of the form {protocol}://{host}:{port}/{appname}/...
  86. /// </summary>
  87. /// <value>The name of the web application.</value>
  88. public string WebApplicationName
  89. {
  90. get { return "mediabrowser"; }
  91. }
  92. /// <summary>
  93. /// Gets the HTTP server URL prefix.
  94. /// </summary>
  95. /// <value>The HTTP server URL prefix.</value>
  96. public string HttpServerUrlPrefix
  97. {
  98. get
  99. {
  100. return "http://+:" + ServerConfigurationManager.Configuration.HttpServerPortNumber + "/" + WebApplicationName + "/";
  101. }
  102. }
  103. /// <summary>
  104. /// Gets the configuration manager.
  105. /// </summary>
  106. /// <returns>IConfigurationManager.</returns>
  107. protected override IConfigurationManager GetConfigurationManager()
  108. {
  109. return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer);
  110. }
  111. /// <summary>
  112. /// Gets or sets the server manager.
  113. /// </summary>
  114. /// <value>The server manager.</value>
  115. private IServerManager ServerManager { get; set; }
  116. /// <summary>
  117. /// Gets or sets the user manager.
  118. /// </summary>
  119. /// <value>The user manager.</value>
  120. public IUserManager UserManager { get; set; }
  121. /// <summary>
  122. /// Gets or sets the library manager.
  123. /// </summary>
  124. /// <value>The library manager.</value>
  125. internal ILibraryManager LibraryManager { get; set; }
  126. /// <summary>
  127. /// Gets or sets the directory watchers.
  128. /// </summary>
  129. /// <value>The directory watchers.</value>
  130. private IDirectoryWatchers DirectoryWatchers { get; set; }
  131. /// <summary>
  132. /// Gets or sets the provider manager.
  133. /// </summary>
  134. /// <value>The provider manager.</value>
  135. private IProviderManager ProviderManager { get; set; }
  136. /// <summary>
  137. /// Gets or sets the HTTP server.
  138. /// </summary>
  139. /// <value>The HTTP server.</value>
  140. private IHttpServer HttpServer { get; set; }
  141. private IDtoService DtoService { get; set; }
  142. private IImageProcessor ImageProcessor { get; set; }
  143. /// <summary>
  144. /// Gets or sets the media encoder.
  145. /// </summary>
  146. /// <value>The media encoder.</value>
  147. private IMediaEncoder MediaEncoder { get; set; }
  148. private ISessionManager SessionManager { get; set; }
  149. private ILiveTvManager LiveTvManager { get; set; }
  150. private ILocalizationManager LocalizationManager { get; set; }
  151. /// <summary>
  152. /// Gets or sets the user data repository.
  153. /// </summary>
  154. /// <value>The user data repository.</value>
  155. private IUserDataManager UserDataManager { get; set; }
  156. private IUserRepository UserRepository { get; set; }
  157. internal IDisplayPreferencesRepository DisplayPreferencesRepository { get; set; }
  158. private IItemRepository ItemRepository { get; set; }
  159. private INotificationsRepository NotificationsRepository { get; set; }
  160. private Task<IHttpServer> _httpServerCreationTask;
  161. /// <summary>
  162. /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
  163. /// </summary>
  164. /// <param name="applicationPaths">The application paths.</param>
  165. /// <param name="logManager">The log manager.</param>
  166. public ApplicationHost(ServerApplicationPaths applicationPaths, ILogManager logManager)
  167. : base(applicationPaths, logManager)
  168. {
  169. }
  170. /// <summary>
  171. /// Gets a value indicating whether this instance can self restart.
  172. /// </summary>
  173. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  174. public override bool CanSelfRestart
  175. {
  176. get { return NativeApp.CanSelfRestart; }
  177. }
  178. /// <summary>
  179. /// Runs the startup tasks.
  180. /// </summary>
  181. /// <returns>Task.</returns>
  182. public override async Task RunStartupTasks()
  183. {
  184. await base.RunStartupTasks().ConfigureAwait(false);
  185. DirectoryWatchers.Start();
  186. Logger.Info("Core startup complete");
  187. Parallel.ForEach(GetExports<IServerEntryPoint>(), entryPoint =>
  188. {
  189. try
  190. {
  191. entryPoint.Run();
  192. }
  193. catch (Exception ex)
  194. {
  195. Logger.ErrorException("Error in {0}", ex, entryPoint.GetType().Name);
  196. }
  197. });
  198. }
  199. /// <summary>
  200. /// Called when [logger loaded].
  201. /// </summary>
  202. protected override void OnLoggerLoaded()
  203. {
  204. base.OnLoggerLoaded();
  205. _httpServerCreationTask = Task.Run(() => ServerFactory.CreateServer(this, LogManager, "Media Browser", "dashboard/index.html"));
  206. }
  207. /// <summary>
  208. /// Registers resources that classes will depend on
  209. /// </summary>
  210. /// <returns>Task.</returns>
  211. protected override async Task RegisterResources()
  212. {
  213. ServerKernel = new Kernel();
  214. await base.RegisterResources().ConfigureAwait(false);
  215. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager));
  216. RegisterSingleInstance<IServerApplicationHost>(this);
  217. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  218. RegisterSingleInstance(ServerKernel);
  219. RegisterSingleInstance(ServerConfigurationManager);
  220. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  221. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  222. var mediaEncoderTask = RegisterMediaEncoder();
  223. UserDataManager = new UserDataManager(LogManager);
  224. RegisterSingleInstance(UserDataManager);
  225. UserRepository = await GetUserRepository().ConfigureAwait(false);
  226. RegisterSingleInstance(UserRepository);
  227. DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
  228. RegisterSingleInstance(DisplayPreferencesRepository);
  229. ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
  230. RegisterSingleInstance(ItemRepository);
  231. UserManager = new UserManager(Logger, ServerConfigurationManager, UserRepository);
  232. RegisterSingleInstance(UserManager);
  233. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => DirectoryWatchers, FileSystemManager);
  234. RegisterSingleInstance(LibraryManager);
  235. DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
  236. RegisterSingleInstance(DirectoryWatchers);
  237. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager, FileSystemManager);
  238. RegisterSingleInstance(ProviderManager);
  239. RegisterSingleInstance<ILibrarySearchEngine>(() => new LuceneSearchEngine(ApplicationPaths, LogManager, LibraryManager));
  240. SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager);
  241. RegisterSingleInstance(SessionManager);
  242. HttpServer = await _httpServerCreationTask.ConfigureAwait(false);
  243. RegisterSingleInstance(HttpServer, false);
  244. ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager);
  245. RegisterSingleInstance(ServerManager);
  246. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager);
  247. RegisterSingleInstance(LocalizationManager);
  248. ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer);
  249. RegisterSingleInstance(ImageProcessor);
  250. DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataManager, ItemRepository, ImageProcessor);
  251. RegisterSingleInstance(DtoService);
  252. LiveTvManager = new LiveTvManager(ApplicationPaths, FileSystemManager, Logger, ItemRepository, ImageProcessor);
  253. RegisterSingleInstance(LiveTvManager);
  254. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  255. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  256. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  257. await ConfigureNotificationsRepository().ConfigureAwait(false);
  258. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask, mediaEncoderTask).ConfigureAwait(false);
  259. SetKernelProperties();
  260. }
  261. protected override INetworkManager CreateNetworkManager()
  262. {
  263. return new NetworkManager();
  264. }
  265. protected override IFileSystem CreateFileSystemManager()
  266. {
  267. return FileSystemFactory.CreateFileSystemManager(LogManager);
  268. }
  269. /// <summary>
  270. /// Registers the media encoder.
  271. /// </summary>
  272. /// <returns>Task.</returns>
  273. private async Task RegisterMediaEncoder()
  274. {
  275. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager).GetFFMpegInfo().ConfigureAwait(false);
  276. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ApplicationPaths, JsonSerializer, info.Path, info.ProbePath, info.Version, FileSystemManager);
  277. RegisterSingleInstance(MediaEncoder);
  278. }
  279. /// <summary>
  280. /// Sets the kernel properties.
  281. /// </summary>
  282. private void SetKernelProperties()
  283. {
  284. Parallel.Invoke(
  285. () => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, Logger, ItemRepository, FileSystemManager),
  286. () => LocalizedStrings.StringFiles = GetExports<LocalizedStringData>(),
  287. SetStaticProperties
  288. );
  289. }
  290. /// <summary>
  291. /// Gets the user repository.
  292. /// </summary>
  293. /// <returns>Task{IUserRepository}.</returns>
  294. private async Task<IUserRepository> GetUserRepository()
  295. {
  296. var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths);
  297. await repo.Initialize().ConfigureAwait(false);
  298. return repo;
  299. }
  300. /// <summary>
  301. /// Configures the repositories.
  302. /// </summary>
  303. /// <returns>Task.</returns>
  304. private async Task ConfigureNotificationsRepository()
  305. {
  306. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths);
  307. await repo.Initialize().ConfigureAwait(false);
  308. NotificationsRepository = repo;
  309. RegisterSingleInstance(NotificationsRepository);
  310. }
  311. /// <summary>
  312. /// Configures the repositories.
  313. /// </summary>
  314. /// <returns>Task.</returns>
  315. private async Task ConfigureDisplayPreferencesRepositories()
  316. {
  317. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  318. }
  319. /// <summary>
  320. /// Configures the item repositories.
  321. /// </summary>
  322. /// <returns>Task.</returns>
  323. private async Task ConfigureItemRepositories()
  324. {
  325. await ItemRepository.Initialize().ConfigureAwait(false);
  326. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  327. }
  328. /// <summary>
  329. /// Configures the user data repositories.
  330. /// </summary>
  331. /// <returns>Task.</returns>
  332. private async Task ConfigureUserDataRepositories()
  333. {
  334. var repo = new SqliteUserDataRepository(ApplicationPaths, JsonSerializer, LogManager);
  335. await repo.Initialize().ConfigureAwait(false);
  336. ((UserDataManager)UserDataManager).Repository = repo;
  337. }
  338. /// <summary>
  339. /// Dirty hacks
  340. /// </summary>
  341. private void SetStaticProperties()
  342. {
  343. // For now there's no real way to inject these properly
  344. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  345. BaseItem.ConfigurationManager = ServerConfigurationManager;
  346. BaseItem.LibraryManager = LibraryManager;
  347. BaseItem.ProviderManager = ProviderManager;
  348. BaseItem.LocalizationManager = LocalizationManager;
  349. BaseItem.ItemRepository = ItemRepository;
  350. User.XmlSerializer = XmlSerializer;
  351. User.UserManager = UserManager;
  352. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  353. Folder.UserManager = UserManager;
  354. BaseItem.FileSystem = FileSystemManager;
  355. }
  356. /// <summary>
  357. /// Finds the parts.
  358. /// </summary>
  359. protected override void FindParts()
  360. {
  361. if (IsFirstRun)
  362. {
  363. RegisterServerWithAdministratorAccess();
  364. }
  365. base.FindParts();
  366. HttpServer.Init(GetExports<IRestfulService>(false));
  367. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  368. StartServer(true);
  369. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  370. GetExports<IVirtualFolderCreator>(),
  371. GetExports<IItemResolver>(),
  372. GetExports<IIntroProvider>(),
  373. GetExports<IBaseItemComparer>(),
  374. GetExports<ILibraryPrescanTask>(),
  375. GetExports<ILibraryPostScanTask>(),
  376. GetExports<IPeoplePrescanTask>(),
  377. GetExports<IMetadataSaver>());
  378. ProviderManager.AddParts(GetExports<BaseMetadataProvider>(), GetExports<IImageProvider>());
  379. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  380. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  381. }
  382. /// <summary>
  383. /// Starts the server.
  384. /// </summary>
  385. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  386. private void StartServer(bool retryOnFailure)
  387. {
  388. try
  389. {
  390. ServerManager.Start(HttpServerUrlPrefix, ServerConfigurationManager.Configuration.EnableHttpLevelLogging);
  391. }
  392. catch (Exception ex)
  393. {
  394. Logger.ErrorException("Error starting http server", ex);
  395. if (retryOnFailure)
  396. {
  397. RegisterServerWithAdministratorAccess();
  398. StartServer(false);
  399. }
  400. else
  401. {
  402. throw;
  403. }
  404. }
  405. ServerManager.StartWebSocketServer();
  406. }
  407. /// <summary>
  408. /// Called when [configuration updated].
  409. /// </summary>
  410. /// <param name="sender">The sender.</param>
  411. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  412. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  413. {
  414. base.OnConfigurationUpdated(sender, e);
  415. HttpServer.EnableHttpRequestLogging = ServerConfigurationManager.Configuration.EnableHttpLevelLogging;
  416. if (!string.Equals(HttpServer.UrlPrefix, HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  417. {
  418. NotifyPendingRestart();
  419. }
  420. else if (!ServerManager.SupportsNativeWebSocket && ServerManager.WebSocketPortNumber != ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  421. {
  422. NotifyPendingRestart();
  423. }
  424. }
  425. /// <summary>
  426. /// Restarts this instance.
  427. /// </summary>
  428. public override async Task Restart()
  429. {
  430. if (!CanSelfRestart)
  431. {
  432. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  433. }
  434. try
  435. {
  436. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  437. }
  438. catch (Exception ex)
  439. {
  440. Logger.ErrorException("Error sending server restart notification", ex);
  441. }
  442. NativeApp.Restart();
  443. }
  444. /// <summary>
  445. /// Gets or sets a value indicating whether this instance can self update.
  446. /// </summary>
  447. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  448. public override bool CanSelfUpdate
  449. {
  450. get
  451. {
  452. #if DEBUG
  453. return false;
  454. #endif
  455. return NativeApp.CanSelfUpdate;
  456. }
  457. }
  458. /// <summary>
  459. /// Gets the composable part assemblies.
  460. /// </summary>
  461. /// <returns>IEnumerable{Assembly}.</returns>
  462. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  463. {
  464. var list = Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  465. .Select(LoadAssembly)
  466. .Where(a => a != null)
  467. .ToList();
  468. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  469. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  470. // Include composable parts in the Api assembly
  471. list.Add(typeof(ApiEntryPoint).Assembly);
  472. // Include composable parts in the Dashboard assembly
  473. list.Add(typeof(DashboardInfo).Assembly);
  474. // Include composable parts in the Model assembly
  475. list.Add(typeof(SystemInfo).Assembly);
  476. // Include composable parts in the Common assembly
  477. list.Add(typeof(IApplicationHost).Assembly);
  478. // Include composable parts in the Controller assembly
  479. list.Add(typeof(Kernel).Assembly);
  480. // Include composable parts in the Providers assembly
  481. list.Add(typeof(ImagesByNameProvider).Assembly);
  482. // Common implementations
  483. list.Add(typeof(TaskManager).Assembly);
  484. // Server implementations
  485. list.Add(typeof(ServerApplicationPaths).Assembly);
  486. list.AddRange(Assemblies.GetAssembliesWithParts());
  487. // Include composable parts in the running assembly
  488. list.Add(GetType().Assembly);
  489. return list;
  490. }
  491. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  492. /// <summary>
  493. /// Gets the system status.
  494. /// </summary>
  495. /// <returns>SystemInfo.</returns>
  496. public virtual SystemInfo GetSystemInfo()
  497. {
  498. return new SystemInfo
  499. {
  500. HasPendingRestart = HasPendingRestart,
  501. Version = ApplicationVersion.ToString(),
  502. IsNetworkDeployed = CanSelfUpdate,
  503. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  504. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  505. FailedPluginAssemblies = FailedAssemblies.ToList(),
  506. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  507. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  508. Id = _systemId,
  509. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  510. MacAddress = GetMacAddress(),
  511. HttpServerPortNumber = ServerConfigurationManager.Configuration.HttpServerPortNumber,
  512. OperatingSystem = Environment.OSVersion.ToString(),
  513. CanSelfRestart = CanSelfRestart,
  514. CanSelfUpdate = CanSelfUpdate
  515. };
  516. }
  517. /// <summary>
  518. /// Gets the mac address.
  519. /// </summary>
  520. /// <returns>System.String.</returns>
  521. private string GetMacAddress()
  522. {
  523. try
  524. {
  525. return NetworkManager.GetMacAddress();
  526. }
  527. catch (Exception ex)
  528. {
  529. Logger.ErrorException("Error getting mac address", ex);
  530. return null;
  531. }
  532. }
  533. /// <summary>
  534. /// Shuts down.
  535. /// </summary>
  536. public override async Task Shutdown()
  537. {
  538. try
  539. {
  540. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  541. }
  542. catch (Exception ex)
  543. {
  544. Logger.ErrorException("Error sending server shutdown notification", ex);
  545. }
  546. NativeApp.Shutdown();
  547. }
  548. /// <summary>
  549. /// Registers the server with administrator access.
  550. /// </summary>
  551. private void RegisterServerWithAdministratorAccess()
  552. {
  553. Logger.Info("Requesting administrative access to authorize http server");
  554. try
  555. {
  556. ServerAuthorization.AuthorizeServer(ServerConfigurationManager.Configuration.HttpServerPortNumber,
  557. HttpServerUrlPrefix, ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber,
  558. UdpServerEntryPoint.PortNumber,
  559. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  560. }
  561. catch (Exception ex)
  562. {
  563. Logger.ErrorException("Error authorizing server", ex);
  564. }
  565. }
  566. /// <summary>
  567. /// Checks for update.
  568. /// </summary>
  569. /// <param name="cancellationToken">The cancellation token.</param>
  570. /// <param name="progress">The progress.</param>
  571. /// <returns>Task{CheckForUpdateResult}.</returns>
  572. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  573. {
  574. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  575. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, null, ApplicationVersion,
  576. ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  577. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  578. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  579. }
  580. /// <summary>
  581. /// Updates the application.
  582. /// </summary>
  583. /// <param name="package">The package that contains the update</param>
  584. /// <param name="cancellationToken">The cancellation token.</param>
  585. /// <param name="progress">The progress.</param>
  586. /// <returns>Task.</returns>
  587. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  588. {
  589. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  590. OnApplicationUpdated(package.version);
  591. }
  592. /// <summary>
  593. /// Creates the HTTP client.
  594. /// </summary>
  595. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  596. /// <returns>HttpClient.</returns>
  597. protected override HttpClient CreateHttpClient(bool enableHttpCompression)
  598. {
  599. return HttpClientFactory.GetHttpClient(enableHttpCompression);
  600. }
  601. protected override void ConfigureAutoRunAtStartup(bool autorun)
  602. {
  603. Autorun.Configure(autorun);
  604. }
  605. }
  606. }