ApplicationHost.cs 26 KB

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