ApplicationHost.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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 IUserDataRepository UserDataRepository { 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. UserDataRepository = new SqliteUserDataRepository(ApplicationPaths, JsonSerializer, LogManager);
  213. RegisterSingleInstance(UserDataRepository);
  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, UserDataRepository, () => 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(UserDataRepository, 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, UserDataRepository, 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 Task ConfigureUserDataRepositories()
  314. {
  315. return UserDataRepository.Initialize();
  316. }
  317. /// <summary>
  318. /// Dirty hacks
  319. /// </summary>
  320. private void SetStaticProperties()
  321. {
  322. // For now there's no real way to inject these properly
  323. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  324. BaseItem.ConfigurationManager = ServerConfigurationManager;
  325. BaseItem.LibraryManager = LibraryManager;
  326. BaseItem.ProviderManager = ProviderManager;
  327. BaseItem.LocalizationManager = LocalizationManager;
  328. BaseItem.ItemRepository = ItemRepository;
  329. User.XmlSerializer = XmlSerializer;
  330. User.UserManager = UserManager;
  331. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  332. }
  333. /// <summary>
  334. /// Finds the parts.
  335. /// </summary>
  336. protected override void FindParts()
  337. {
  338. if (IsFirstRun)
  339. {
  340. RegisterServerWithAdministratorAccess();
  341. }
  342. base.FindParts();
  343. HttpServer.Init(GetExports<IRestfulService>(false));
  344. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  345. StartServer(true);
  346. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  347. GetExports<IVirtualFolderCreator>(),
  348. GetExports<IItemResolver>(),
  349. GetExports<IIntroProvider>(),
  350. GetExports<IBaseItemComparer>(),
  351. GetExports<ILibraryPrescanTask>(),
  352. GetExports<ILibraryPostScanTask>(),
  353. GetExports<IMetadataSaver>());
  354. ProviderManager.AddParts(GetExports<BaseMetadataProvider>());
  355. SessionManager.AddParts(GetExports<ISessionRemoteController>());
  356. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  357. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  358. }
  359. /// <summary>
  360. /// Starts the server.
  361. /// </summary>
  362. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  363. private void StartServer(bool retryOnFailure)
  364. {
  365. try
  366. {
  367. ServerManager.Start(HttpServerUrlPrefix, ServerConfigurationManager.Configuration.EnableHttpLevelLogging);
  368. }
  369. catch
  370. {
  371. if (retryOnFailure)
  372. {
  373. RegisterServerWithAdministratorAccess();
  374. StartServer(false);
  375. }
  376. else
  377. {
  378. throw;
  379. }
  380. }
  381. ServerManager.StartWebSocketServer();
  382. }
  383. /// <summary>
  384. /// Called when [configuration updated].
  385. /// </summary>
  386. /// <param name="sender">The sender.</param>
  387. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  388. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  389. {
  390. base.OnConfigurationUpdated(sender, e);
  391. HttpServer.EnableHttpRequestLogging = ServerConfigurationManager.Configuration.EnableHttpLevelLogging;
  392. if (!string.Equals(HttpServer.UrlPrefix, HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  393. {
  394. NotifyPendingRestart();
  395. }
  396. else if (!ServerManager.SupportsNativeWebSocket && ServerManager.WebSocketPortNumber != ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  397. {
  398. NotifyPendingRestart();
  399. }
  400. }
  401. /// <summary>
  402. /// Restarts this instance.
  403. /// </summary>
  404. public override async Task Restart()
  405. {
  406. try
  407. {
  408. await ServerManager.SendWebSocketMessageAsync("ServerRestarting", () => string.Empty, CancellationToken.None).ConfigureAwait(false);
  409. }
  410. catch (Exception ex)
  411. {
  412. Logger.ErrorException("Error sending server restart web socket message", ex);
  413. }
  414. NativeApp.Restart();
  415. }
  416. /// <summary>
  417. /// Gets or sets a value indicating whether this instance can self update.
  418. /// </summary>
  419. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  420. public override bool CanSelfUpdate
  421. {
  422. get
  423. {
  424. #if DEBUG
  425. return false;
  426. #endif
  427. return true;
  428. }
  429. }
  430. /// <summary>
  431. /// Gets the composable part assemblies.
  432. /// </summary>
  433. /// <returns>IEnumerable{Assembly}.</returns>
  434. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  435. {
  436. var list = Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  437. .Select(LoadAssembly)
  438. .Where(a => a != null)
  439. .ToList();
  440. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  441. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  442. // Include composable parts in the Api assembly
  443. list.Add(typeof(ApiEntryPoint).Assembly);
  444. // Include composable parts in the Dashboard assembly
  445. list.Add(typeof(DashboardInfo).Assembly);
  446. // Include composable parts in the Model assembly
  447. list.Add(typeof(SystemInfo).Assembly);
  448. // Include composable parts in the Common assembly
  449. list.Add(typeof(IApplicationHost).Assembly);
  450. // Include composable parts in the Controller assembly
  451. list.Add(typeof(Kernel).Assembly);
  452. // Include composable parts in the Providers assembly
  453. list.Add(typeof(ImagesByNameProvider).Assembly);
  454. // Common implementations
  455. list.Add(typeof(TaskManager).Assembly);
  456. // Server implementations
  457. list.Add(typeof(ServerApplicationPaths).Assembly);
  458. list.AddRange(Assemblies.GetAssembliesWithParts());
  459. // Include composable parts in the running assembly
  460. list.Add(GetType().Assembly);
  461. return list;
  462. }
  463. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  464. /// <summary>
  465. /// Gets the system status.
  466. /// </summary>
  467. /// <returns>SystemInfo.</returns>
  468. public virtual SystemInfo GetSystemInfo()
  469. {
  470. return new SystemInfo
  471. {
  472. HasPendingRestart = HasPendingRestart,
  473. Version = ApplicationVersion.ToString(),
  474. IsNetworkDeployed = CanSelfUpdate,
  475. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  476. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  477. FailedPluginAssemblies = FailedAssemblies.ToList(),
  478. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  479. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  480. Id = _systemId,
  481. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  482. MacAddress = GetMacAddress(),
  483. HttpServerPortNumber = ServerConfigurationManager.Configuration.HttpServerPortNumber,
  484. OperatingSystem = Environment.OSVersion.ToString()
  485. };
  486. }
  487. /// <summary>
  488. /// Gets the mac address.
  489. /// </summary>
  490. /// <returns>System.String.</returns>
  491. private string GetMacAddress()
  492. {
  493. try
  494. {
  495. return NetworkManager.GetMacAddress();
  496. }
  497. catch (Exception ex)
  498. {
  499. Logger.ErrorException("Error getting mac address", ex);
  500. return null;
  501. }
  502. }
  503. /// <summary>
  504. /// Shuts down.
  505. /// </summary>
  506. public override async Task Shutdown()
  507. {
  508. try
  509. {
  510. await ServerManager.SendWebSocketMessageAsync("ServerShuttingDown", () => string.Empty, CancellationToken.None).ConfigureAwait(false);
  511. }
  512. catch (Exception ex)
  513. {
  514. Logger.ErrorException("Error sending server shutdown web socket message", ex);
  515. }
  516. NativeApp.Shutdown();
  517. }
  518. /// <summary>
  519. /// Registers the server with administrator access.
  520. /// </summary>
  521. private void RegisterServerWithAdministratorAccess()
  522. {
  523. Logger.Info("Requesting administrative access to authorize http server");
  524. try
  525. {
  526. ServerAuthorization.AuthorizeServer(ServerConfigurationManager.Configuration.HttpServerPortNumber,
  527. HttpServerUrlPrefix, ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber,
  528. UdpServerEntryPoint.PortNumber,
  529. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  530. }
  531. catch (Exception ex)
  532. {
  533. Logger.ErrorException("Error authorizing server", ex);
  534. }
  535. }
  536. /// <summary>
  537. /// Checks for update.
  538. /// </summary>
  539. /// <param name="cancellationToken">The cancellation token.</param>
  540. /// <param name="progress">The progress.</param>
  541. /// <returns>Task{CheckForUpdateResult}.</returns>
  542. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  543. {
  544. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  545. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, ApplicationVersion,
  546. ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  547. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  548. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  549. }
  550. /// <summary>
  551. /// Updates the application.
  552. /// </summary>
  553. /// <param name="package">The package that contains the update</param>
  554. /// <param name="cancellationToken">The cancellation token.</param>
  555. /// <param name="progress">The progress.</param>
  556. /// <returns>Task.</returns>
  557. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  558. {
  559. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  560. OnApplicationUpdated(package.version);
  561. }
  562. /// <summary>
  563. /// Gets the HTTP message handler.
  564. /// </summary>
  565. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  566. /// <returns>HttpMessageHandler.</returns>
  567. protected override HttpMessageHandler GetHttpMessageHandler(bool enableHttpCompression)
  568. {
  569. return HttpMessageHandlerFactory.GetHttpMessageHandler(enableHttpCompression);
  570. }
  571. protected override void ConfigureAutoRunAtStartup(bool autorun)
  572. {
  573. Autorun.Configure(autorun);
  574. }
  575. }
  576. }