ApplicationHost.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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.IO;
  8. using MediaBrowser.Common.Implementations.ScheduledTasks;
  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.IO;
  29. using MediaBrowser.Model.Logging;
  30. using MediaBrowser.Model.MediaInfo;
  31. using MediaBrowser.Model.System;
  32. using MediaBrowser.Model.Updates;
  33. using MediaBrowser.Providers;
  34. using MediaBrowser.Server.Implementations;
  35. using MediaBrowser.Server.Implementations.BdInfo;
  36. using MediaBrowser.Server.Implementations.Configuration;
  37. using MediaBrowser.Server.Implementations.Drawing;
  38. using MediaBrowser.Server.Implementations.Dto;
  39. using MediaBrowser.Server.Implementations.EntryPoints;
  40. using MediaBrowser.Server.Implementations.HttpServer;
  41. using MediaBrowser.Server.Implementations.IO;
  42. using MediaBrowser.Server.Implementations.Library;
  43. using MediaBrowser.Server.Implementations.LiveTv;
  44. using MediaBrowser.Server.Implementations.Localization;
  45. using MediaBrowser.Server.Implementations.MediaEncoder;
  46. using MediaBrowser.Server.Implementations.Persistence;
  47. using MediaBrowser.Server.Implementations.Providers;
  48. using MediaBrowser.Server.Implementations.ServerManager;
  49. using MediaBrowser.Server.Implementations.Session;
  50. using MediaBrowser.Server.Implementations.WebSocket;
  51. using MediaBrowser.ServerApplication.FFMpeg;
  52. using MediaBrowser.ServerApplication.Native;
  53. using MediaBrowser.WebDashboard.Api;
  54. using System;
  55. using System.Collections.Generic;
  56. using System.IO;
  57. using System.Linq;
  58. using System.Net.Http;
  59. using System.Reflection;
  60. using System.Threading;
  61. using System.Threading.Tasks;
  62. namespace MediaBrowser.ServerApplication
  63. {
  64. /// <summary>
  65. /// Class CompositionRoot
  66. /// </summary>
  67. public class ApplicationHost : BaseApplicationHost<ServerApplicationPaths>, IServerApplicationHost
  68. {
  69. /// <summary>
  70. /// Gets the server kernel.
  71. /// </summary>
  72. /// <value>The server kernel.</value>
  73. protected Kernel ServerKernel { get; set; }
  74. /// <summary>
  75. /// Gets the server configuration manager.
  76. /// </summary>
  77. /// <value>The server configuration manager.</value>
  78. public IServerConfigurationManager ServerConfigurationManager
  79. {
  80. get { return (IServerConfigurationManager)ConfigurationManager; }
  81. }
  82. /// <summary>
  83. /// Gets the name of the web application that can be used for url building.
  84. /// All api urls will be of the form {protocol}://{host}:{port}/{appname}/...
  85. /// </summary>
  86. /// <value>The name of the web application.</value>
  87. public string WebApplicationName
  88. {
  89. get { return "mediabrowser"; }
  90. }
  91. /// <summary>
  92. /// Gets the HTTP server URL prefix.
  93. /// </summary>
  94. /// <value>The HTTP server URL prefix.</value>
  95. public string HttpServerUrlPrefix
  96. {
  97. get
  98. {
  99. return "http://+:" + ServerConfigurationManager.Configuration.HttpServerPortNumber + "/" + WebApplicationName + "/";
  100. }
  101. }
  102. /// <summary>
  103. /// Gets the configuration manager.
  104. /// </summary>
  105. /// <returns>IConfigurationManager.</returns>
  106. protected override IConfigurationManager GetConfigurationManager()
  107. {
  108. return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer);
  109. }
  110. /// <summary>
  111. /// Gets or sets the server manager.
  112. /// </summary>
  113. /// <value>The server manager.</value>
  114. private IServerManager ServerManager { get; set; }
  115. /// <summary>
  116. /// Gets or sets the user manager.
  117. /// </summary>
  118. /// <value>The user manager.</value>
  119. public IUserManager UserManager { get; set; }
  120. /// <summary>
  121. /// Gets or sets the library manager.
  122. /// </summary>
  123. /// <value>The library manager.</value>
  124. internal ILibraryManager LibraryManager { get; set; }
  125. /// <summary>
  126. /// Gets or sets the directory watchers.
  127. /// </summary>
  128. /// <value>The directory watchers.</value>
  129. private IDirectoryWatchers DirectoryWatchers { get; set; }
  130. /// <summary>
  131. /// Gets or sets the provider manager.
  132. /// </summary>
  133. /// <value>The provider manager.</value>
  134. private IProviderManager ProviderManager { get; set; }
  135. /// <summary>
  136. /// Gets or sets the HTTP server.
  137. /// </summary>
  138. /// <value>The HTTP server.</value>
  139. private IHttpServer HttpServer { get; set; }
  140. private IDtoService DtoService { get; set; }
  141. private IImageProcessor ImageProcessor { get; set; }
  142. /// <summary>
  143. /// Gets or sets the media encoder.
  144. /// </summary>
  145. /// <value>The media encoder.</value>
  146. private IMediaEncoder MediaEncoder { get; set; }
  147. private IIsoManager IsoManager { 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 IUserDataRepository UserDataRepository { 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. /// Runs the startup tasks.
  172. /// </summary>
  173. /// <returns>Task.</returns>
  174. public override async Task RunStartupTasks()
  175. {
  176. await base.RunStartupTasks().ConfigureAwait(false);
  177. DirectoryWatchers.Start();
  178. Logger.Info("Core startup complete");
  179. Parallel.ForEach(GetExports<IServerEntryPoint>(), entryPoint =>
  180. {
  181. try
  182. {
  183. entryPoint.Run();
  184. }
  185. catch (Exception ex)
  186. {
  187. Logger.ErrorException("Error in {0}", ex, entryPoint.GetType().Name);
  188. }
  189. });
  190. }
  191. /// <summary>
  192. /// Called when [logger loaded].
  193. /// </summary>
  194. protected override void OnLoggerLoaded()
  195. {
  196. base.OnLoggerLoaded();
  197. _httpServerCreationTask = Task.Run(() => ServerFactory.CreateServer(this, LogManager, "Media Browser", "dashboard/index.html"));
  198. }
  199. /// <summary>
  200. /// Registers resources that classes will depend on
  201. /// </summary>
  202. /// <returns>Task.</returns>
  203. protected override async Task RegisterResources()
  204. {
  205. ServerKernel = new Kernel();
  206. await base.RegisterResources().ConfigureAwait(false);
  207. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager));
  208. RegisterSingleInstance<IServerApplicationHost>(this);
  209. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  210. RegisterSingleInstance(ServerKernel);
  211. RegisterSingleInstance(ServerConfigurationManager);
  212. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  213. IsoManager = new IsoManager();
  214. RegisterSingleInstance(IsoManager);
  215. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  216. var mediaEncoderTask = RegisterMediaEncoder();
  217. UserDataRepository = new SqliteUserDataRepository(ApplicationPaths, JsonSerializer, LogManager);
  218. RegisterSingleInstance(UserDataRepository);
  219. UserRepository = await GetUserRepository().ConfigureAwait(false);
  220. RegisterSingleInstance(UserRepository);
  221. DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
  222. RegisterSingleInstance(DisplayPreferencesRepository);
  223. ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
  224. RegisterSingleInstance(ItemRepository);
  225. UserManager = new UserManager(Logger, ServerConfigurationManager, UserRepository);
  226. RegisterSingleInstance(UserManager);
  227. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataRepository, () => DirectoryWatchers);
  228. RegisterSingleInstance(LibraryManager);
  229. DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager);
  230. RegisterSingleInstance(DirectoryWatchers);
  231. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager, LibraryManager);
  232. RegisterSingleInstance(ProviderManager);
  233. RegisterSingleInstance<ILibrarySearchEngine>(() => new LuceneSearchEngine(ApplicationPaths, LogManager, LibraryManager));
  234. SessionManager = new SessionManager(UserDataRepository, ServerConfigurationManager, Logger, UserRepository);
  235. RegisterSingleInstance<ISessionManager>(SessionManager);
  236. HttpServer = await _httpServerCreationTask.ConfigureAwait(false);
  237. RegisterSingleInstance(HttpServer, false);
  238. ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager);
  239. RegisterSingleInstance(ServerManager);
  240. LocalizationManager = new LocalizationManager(ServerConfigurationManager);
  241. RegisterSingleInstance(LocalizationManager);
  242. ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths);
  243. RegisterSingleInstance(ImageProcessor);
  244. DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataRepository, ItemRepository, ImageProcessor);
  245. RegisterSingleInstance(DtoService);
  246. LiveTvManager = new LiveTvManager();
  247. RegisterSingleInstance(LiveTvManager);
  248. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  249. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  250. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  251. await ConfigureNotificationsRepository().ConfigureAwait(false);
  252. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask, mediaEncoderTask).ConfigureAwait(false);
  253. SetKernelProperties();
  254. }
  255. /// <summary>
  256. /// Registers the media encoder.
  257. /// </summary>
  258. /// <returns>Task.</returns>
  259. private async Task RegisterMediaEncoder()
  260. {
  261. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient).GetFFMpegInfo().ConfigureAwait(false);
  262. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ApplicationPaths, JsonSerializer, info.Path, info.ProbePath, info.Version);
  263. RegisterSingleInstance(MediaEncoder);
  264. }
  265. /// <summary>
  266. /// Sets the kernel properties.
  267. /// </summary>
  268. private void SetKernelProperties()
  269. {
  270. Parallel.Invoke(
  271. () => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, Logger, ItemRepository),
  272. () => LocalizedStrings.StringFiles = GetExports<LocalizedStringData>(),
  273. SetStaticProperties
  274. );
  275. }
  276. private async Task<IUserRepository> GetUserRepository()
  277. {
  278. var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths);
  279. await repo.Initialize().ConfigureAwait(false);
  280. return repo;
  281. }
  282. /// <summary>
  283. /// Configures the repositories.
  284. /// </summary>
  285. /// <returns>Task.</returns>
  286. private async Task ConfigureNotificationsRepository()
  287. {
  288. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths);
  289. await repo.Initialize().ConfigureAwait(false);
  290. NotificationsRepository = repo;
  291. RegisterSingleInstance(NotificationsRepository);
  292. }
  293. /// <summary>
  294. /// Configures the repositories.
  295. /// </summary>
  296. /// <returns>Task.</returns>
  297. private async Task ConfigureDisplayPreferencesRepositories()
  298. {
  299. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  300. }
  301. /// <summary>
  302. /// Configures the item repositories.
  303. /// </summary>
  304. /// <returns>Task.</returns>
  305. private async Task ConfigureItemRepositories()
  306. {
  307. await ItemRepository.Initialize().ConfigureAwait(false);
  308. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  309. }
  310. /// <summary>
  311. /// Configures the user data repositories.
  312. /// </summary>
  313. /// <returns>Task.</returns>
  314. private Task ConfigureUserDataRepositories()
  315. {
  316. return UserDataRepository.Initialize();
  317. }
  318. /// <summary>
  319. /// Dirty hacks
  320. /// </summary>
  321. private void SetStaticProperties()
  322. {
  323. // For now there's no real way to inject these properly
  324. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  325. BaseItem.ConfigurationManager = ServerConfigurationManager;
  326. BaseItem.LibraryManager = LibraryManager;
  327. BaseItem.ProviderManager = ProviderManager;
  328. BaseItem.LocalizationManager = LocalizationManager;
  329. BaseItem.ItemRepository = ItemRepository;
  330. User.XmlSerializer = XmlSerializer;
  331. User.UserManager = UserManager;
  332. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  333. }
  334. /// <summary>
  335. /// Finds the parts.
  336. /// </summary>
  337. protected override void FindParts()
  338. {
  339. if (IsFirstRun)
  340. {
  341. RegisterServerWithAdministratorAccess();
  342. }
  343. base.FindParts();
  344. HttpServer.Init(GetExports<IRestfulService>(false));
  345. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  346. StartServer(true);
  347. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  348. GetExports<IVirtualFolderCreator>(),
  349. GetExports<IItemResolver>(),
  350. GetExports<IIntroProvider>(),
  351. GetExports<IBaseItemComparer>(),
  352. GetExports<ILibraryPrescanTask>(),
  353. GetExports<ILibraryPostScanTask>(),
  354. GetExports<IMetadataSaver>());
  355. ProviderManager.AddParts(GetExports<BaseMetadataProvider>());
  356. IsoManager.AddParts(GetExports<IIsoMounter>());
  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 ConfigurationManager.CommonConfiguration.EnableAutoUpdate;
  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. };
  487. }
  488. /// <summary>
  489. /// Gets the mac address.
  490. /// </summary>
  491. /// <returns>System.String.</returns>
  492. private string GetMacAddress()
  493. {
  494. try
  495. {
  496. return NetworkManager.GetMacAddress();
  497. }
  498. catch (Exception ex)
  499. {
  500. Logger.ErrorException("Error getting mac address", ex);
  501. return null;
  502. }
  503. }
  504. /// <summary>
  505. /// Shuts down.
  506. /// </summary>
  507. public override async Task Shutdown()
  508. {
  509. try
  510. {
  511. await ServerManager.SendWebSocketMessageAsync("ServerShuttingDown", () => string.Empty, CancellationToken.None).ConfigureAwait(false);
  512. }
  513. catch (Exception ex)
  514. {
  515. Logger.ErrorException("Error sending server shutdown web socket message", ex);
  516. }
  517. NativeApp.Shutdown();
  518. }
  519. /// <summary>
  520. /// Registers the server with administrator access.
  521. /// </summary>
  522. private void RegisterServerWithAdministratorAccess()
  523. {
  524. Logger.Info("Requesting administrative access to authorize http server");
  525. try
  526. {
  527. ServerAuthorization.AuthorizeServer(ServerConfigurationManager.Configuration.HttpServerPortNumber,
  528. HttpServerUrlPrefix, ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber,
  529. UdpServerEntryPoint.PortNumber,
  530. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  531. }
  532. catch (Exception ex)
  533. {
  534. Logger.ErrorException("Error authorizing server", ex);
  535. }
  536. }
  537. /// <summary>
  538. /// Checks for update.
  539. /// </summary>
  540. /// <param name="cancellationToken">The cancellation token.</param>
  541. /// <param name="progress">The progress.</param>
  542. /// <returns>Task{CheckForUpdateResult}.</returns>
  543. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  544. {
  545. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  546. var package = availablePackages.FirstOrDefault(p => p.name.Equals(Constants.MbServerPkgName, StringComparison.OrdinalIgnoreCase));
  547. if (package == null)
  548. {
  549. return null;
  550. }
  551. var version = package.versions
  552. .OrderByDescending(v => v.version)
  553. .FirstOrDefault(v => v.classification <= ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  554. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  555. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  556. }
  557. /// <summary>
  558. /// Updates the application.
  559. /// </summary>
  560. /// <param name="package">The package that contains the update</param>
  561. /// <param name="cancellationToken">The cancellation token.</param>
  562. /// <param name="progress">The progress.</param>
  563. /// <returns>Task.</returns>
  564. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  565. {
  566. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  567. OnApplicationUpdated(package.version);
  568. }
  569. /// <summary>
  570. /// Gets the HTTP message handler.
  571. /// </summary>
  572. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  573. /// <returns>HttpMessageHandler.</returns>
  574. protected override HttpMessageHandler GetHttpMessageHandler(bool enableHttpCompression)
  575. {
  576. return HttpMessageHandlerFactory.GetHttpMessageHandler(enableHttpCompression);
  577. }
  578. protected override void ConfigureAutoRunAtStartup(bool autorun)
  579. {
  580. Autorun.Configure(autorun);
  581. }
  582. }
  583. }