ApplicationHost.cs 26 KB

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