ApplicationHost.cs 26 KB

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