ApplicationHost.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. /// Gets a value indicating whether this instance can self restart.
  170. /// </summary>
  171. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  172. public override bool CanSelfRestart
  173. {
  174. get { return NativeApp.CanSelfRestart; }
  175. }
  176. /// <summary>
  177. /// Runs the startup tasks.
  178. /// </summary>
  179. /// <returns>Task.</returns>
  180. public override async Task RunStartupTasks()
  181. {
  182. await base.RunStartupTasks().ConfigureAwait(false);
  183. DirectoryWatchers.Start();
  184. Logger.Info("Core startup complete");
  185. Parallel.ForEach(GetExports<IServerEntryPoint>(), entryPoint =>
  186. {
  187. try
  188. {
  189. entryPoint.Run();
  190. }
  191. catch (Exception ex)
  192. {
  193. Logger.ErrorException("Error in {0}", ex, entryPoint.GetType().Name);
  194. }
  195. });
  196. }
  197. /// <summary>
  198. /// Called when [logger loaded].
  199. /// </summary>
  200. protected override void OnLoggerLoaded()
  201. {
  202. base.OnLoggerLoaded();
  203. _httpServerCreationTask = Task.Run(() => ServerFactory.CreateServer(this, LogManager, "Media Browser", "dashboard/index.html"));
  204. }
  205. /// <summary>
  206. /// Registers resources that classes will depend on
  207. /// </summary>
  208. /// <returns>Task.</returns>
  209. protected override async Task RegisterResources()
  210. {
  211. ServerKernel = new Kernel();
  212. await base.RegisterResources().ConfigureAwait(false);
  213. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager));
  214. RegisterSingleInstance<IServerApplicationHost>(this);
  215. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  216. RegisterSingleInstance(ServerKernel);
  217. RegisterSingleInstance(ServerConfigurationManager);
  218. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  219. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  220. var mediaEncoderTask = RegisterMediaEncoder();
  221. UserDataManager = new UserDataManager(LogManager);
  222. RegisterSingleInstance(UserDataManager);
  223. UserRepository = await GetUserRepository().ConfigureAwait(false);
  224. RegisterSingleInstance(UserRepository);
  225. DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
  226. RegisterSingleInstance(DisplayPreferencesRepository);
  227. ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
  228. RegisterSingleInstance(ItemRepository);
  229. UserManager = new UserManager(Logger, ServerConfigurationManager, UserRepository);
  230. RegisterSingleInstance(UserManager);
  231. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => DirectoryWatchers);
  232. RegisterSingleInstance(LibraryManager);
  233. DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager);
  234. RegisterSingleInstance(DirectoryWatchers);
  235. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager, LibraryManager);
  236. RegisterSingleInstance(ProviderManager);
  237. RegisterSingleInstance<ILibrarySearchEngine>(() => new LuceneSearchEngine(ApplicationPaths, LogManager, LibraryManager));
  238. SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager);
  239. RegisterSingleInstance(SessionManager);
  240. HttpServer = await _httpServerCreationTask.ConfigureAwait(false);
  241. RegisterSingleInstance(HttpServer, false);
  242. ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager);
  243. RegisterSingleInstance(ServerManager);
  244. LocalizationManager = new LocalizationManager(ServerConfigurationManager);
  245. RegisterSingleInstance(LocalizationManager);
  246. ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths);
  247. RegisterSingleInstance(ImageProcessor);
  248. DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataManager, ItemRepository, ImageProcessor);
  249. RegisterSingleInstance(DtoService);
  250. LiveTvManager = new LiveTvManager();
  251. RegisterSingleInstance(LiveTvManager);
  252. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  253. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  254. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  255. await ConfigureNotificationsRepository().ConfigureAwait(false);
  256. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask, mediaEncoderTask).ConfigureAwait(false);
  257. SetKernelProperties();
  258. }
  259. protected override INetworkManager CreateNetworkManager()
  260. {
  261. return new NetworkManager();
  262. }
  263. /// <summary>
  264. /// Registers the media encoder.
  265. /// </summary>
  266. /// <returns>Task.</returns>
  267. private async Task RegisterMediaEncoder()
  268. {
  269. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient).GetFFMpegInfo().ConfigureAwait(false);
  270. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ApplicationPaths, JsonSerializer, info.Path, info.ProbePath, info.Version);
  271. RegisterSingleInstance(MediaEncoder);
  272. }
  273. /// <summary>
  274. /// Sets the kernel properties.
  275. /// </summary>
  276. private void SetKernelProperties()
  277. {
  278. Parallel.Invoke(
  279. () => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, Logger, ItemRepository),
  280. () => LocalizedStrings.StringFiles = GetExports<LocalizedStringData>(),
  281. SetStaticProperties
  282. );
  283. }
  284. /// <summary>
  285. /// Gets the user repository.
  286. /// </summary>
  287. /// <returns>Task{IUserRepository}.</returns>
  288. private async Task<IUserRepository> GetUserRepository()
  289. {
  290. var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths);
  291. await repo.Initialize().ConfigureAwait(false);
  292. return repo;
  293. }
  294. /// <summary>
  295. /// Configures the repositories.
  296. /// </summary>
  297. /// <returns>Task.</returns>
  298. private async Task ConfigureNotificationsRepository()
  299. {
  300. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths);
  301. await repo.Initialize().ConfigureAwait(false);
  302. NotificationsRepository = repo;
  303. RegisterSingleInstance(NotificationsRepository);
  304. }
  305. /// <summary>
  306. /// Configures the repositories.
  307. /// </summary>
  308. /// <returns>Task.</returns>
  309. private async Task ConfigureDisplayPreferencesRepositories()
  310. {
  311. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  312. }
  313. /// <summary>
  314. /// Configures the item repositories.
  315. /// </summary>
  316. /// <returns>Task.</returns>
  317. private async Task ConfigureItemRepositories()
  318. {
  319. await ItemRepository.Initialize().ConfigureAwait(false);
  320. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  321. }
  322. /// <summary>
  323. /// Configures the user data repositories.
  324. /// </summary>
  325. /// <returns>Task.</returns>
  326. private async Task ConfigureUserDataRepositories()
  327. {
  328. var repo = new SqliteUserDataRepository(ApplicationPaths, JsonSerializer, LogManager);
  329. await repo.Initialize().ConfigureAwait(false);
  330. ((UserDataManager)UserDataManager).Repository = repo;
  331. }
  332. /// <summary>
  333. /// Dirty hacks
  334. /// </summary>
  335. private void SetStaticProperties()
  336. {
  337. // For now there's no real way to inject these properly
  338. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  339. BaseItem.ConfigurationManager = ServerConfigurationManager;
  340. BaseItem.LibraryManager = LibraryManager;
  341. BaseItem.ProviderManager = ProviderManager;
  342. BaseItem.LocalizationManager = LocalizationManager;
  343. BaseItem.ItemRepository = ItemRepository;
  344. User.XmlSerializer = XmlSerializer;
  345. User.UserManager = UserManager;
  346. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  347. Folder.UserManager = UserManager;
  348. }
  349. /// <summary>
  350. /// Finds the parts.
  351. /// </summary>
  352. protected override void FindParts()
  353. {
  354. if (IsFirstRun)
  355. {
  356. RegisterServerWithAdministratorAccess();
  357. }
  358. base.FindParts();
  359. HttpServer.Init(GetExports<IRestfulService>(false));
  360. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  361. StartServer(true);
  362. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  363. GetExports<IVirtualFolderCreator>(),
  364. GetExports<IItemResolver>(),
  365. GetExports<IIntroProvider>(),
  366. GetExports<IBaseItemComparer>(),
  367. GetExports<ILibraryPrescanTask>(),
  368. GetExports<ILibraryPostScanTask>(),
  369. GetExports<IPeoplePrescanTask>(),
  370. GetExports<IMetadataSaver>());
  371. ProviderManager.AddParts(GetExports<BaseMetadataProvider>());
  372. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  373. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  374. }
  375. /// <summary>
  376. /// Starts the server.
  377. /// </summary>
  378. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  379. private void StartServer(bool retryOnFailure)
  380. {
  381. try
  382. {
  383. ServerManager.Start(HttpServerUrlPrefix, ServerConfigurationManager.Configuration.EnableHttpLevelLogging);
  384. }
  385. catch (Exception ex)
  386. {
  387. Logger.ErrorException("Error starting http server", ex);
  388. if (retryOnFailure)
  389. {
  390. RegisterServerWithAdministratorAccess();
  391. StartServer(false);
  392. }
  393. else
  394. {
  395. throw;
  396. }
  397. }
  398. ServerManager.StartWebSocketServer();
  399. }
  400. /// <summary>
  401. /// Called when [configuration updated].
  402. /// </summary>
  403. /// <param name="sender">The sender.</param>
  404. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  405. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  406. {
  407. base.OnConfigurationUpdated(sender, e);
  408. HttpServer.EnableHttpRequestLogging = ServerConfigurationManager.Configuration.EnableHttpLevelLogging;
  409. if (!string.Equals(HttpServer.UrlPrefix, HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  410. {
  411. NotifyPendingRestart();
  412. }
  413. else if (!ServerManager.SupportsNativeWebSocket && ServerManager.WebSocketPortNumber != ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  414. {
  415. NotifyPendingRestart();
  416. }
  417. }
  418. /// <summary>
  419. /// Restarts this instance.
  420. /// </summary>
  421. public override async Task Restart()
  422. {
  423. if (!CanSelfRestart)
  424. {
  425. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  426. }
  427. try
  428. {
  429. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  430. }
  431. catch (Exception ex)
  432. {
  433. Logger.ErrorException("Error sending server restart notification", ex);
  434. }
  435. NativeApp.Restart();
  436. }
  437. /// <summary>
  438. /// Gets or sets a value indicating whether this instance can self update.
  439. /// </summary>
  440. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  441. public override bool CanSelfUpdate
  442. {
  443. get
  444. {
  445. #if DEBUG
  446. return false;
  447. #endif
  448. return NativeApp.CanSelfUpdate;
  449. }
  450. }
  451. /// <summary>
  452. /// Gets the composable part assemblies.
  453. /// </summary>
  454. /// <returns>IEnumerable{Assembly}.</returns>
  455. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  456. {
  457. var list = Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  458. .Select(LoadAssembly)
  459. .Where(a => a != null)
  460. .ToList();
  461. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  462. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  463. // Include composable parts in the Api assembly
  464. list.Add(typeof(ApiEntryPoint).Assembly);
  465. // Include composable parts in the Dashboard assembly
  466. list.Add(typeof(DashboardInfo).Assembly);
  467. // Include composable parts in the Model assembly
  468. list.Add(typeof(SystemInfo).Assembly);
  469. // Include composable parts in the Common assembly
  470. list.Add(typeof(IApplicationHost).Assembly);
  471. // Include composable parts in the Controller assembly
  472. list.Add(typeof(Kernel).Assembly);
  473. // Include composable parts in the Providers assembly
  474. list.Add(typeof(ImagesByNameProvider).Assembly);
  475. // Common implementations
  476. list.Add(typeof(TaskManager).Assembly);
  477. // Server implementations
  478. list.Add(typeof(ServerApplicationPaths).Assembly);
  479. list.AddRange(Assemblies.GetAssembliesWithParts());
  480. // Include composable parts in the running assembly
  481. list.Add(GetType().Assembly);
  482. return list;
  483. }
  484. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  485. /// <summary>
  486. /// Gets the system status.
  487. /// </summary>
  488. /// <returns>SystemInfo.</returns>
  489. public virtual SystemInfo GetSystemInfo()
  490. {
  491. return new SystemInfo
  492. {
  493. HasPendingRestart = HasPendingRestart,
  494. Version = ApplicationVersion.ToString(),
  495. IsNetworkDeployed = CanSelfUpdate,
  496. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  497. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  498. FailedPluginAssemblies = FailedAssemblies.ToList(),
  499. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  500. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  501. Id = _systemId,
  502. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  503. MacAddress = GetMacAddress(),
  504. HttpServerPortNumber = ServerConfigurationManager.Configuration.HttpServerPortNumber,
  505. OperatingSystem = Environment.OSVersion.ToString(),
  506. CanSelfRestart = CanSelfRestart,
  507. CanSelfUpdate = CanSelfUpdate
  508. };
  509. }
  510. /// <summary>
  511. /// Gets the mac address.
  512. /// </summary>
  513. /// <returns>System.String.</returns>
  514. private string GetMacAddress()
  515. {
  516. try
  517. {
  518. return NetworkManager.GetMacAddress();
  519. }
  520. catch (Exception ex)
  521. {
  522. Logger.ErrorException("Error getting mac address", ex);
  523. return null;
  524. }
  525. }
  526. /// <summary>
  527. /// Shuts down.
  528. /// </summary>
  529. public override async Task Shutdown()
  530. {
  531. try
  532. {
  533. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  534. }
  535. catch (Exception ex)
  536. {
  537. Logger.ErrorException("Error sending server shutdown notification", ex);
  538. }
  539. NativeApp.Shutdown();
  540. }
  541. /// <summary>
  542. /// Registers the server with administrator access.
  543. /// </summary>
  544. private void RegisterServerWithAdministratorAccess()
  545. {
  546. Logger.Info("Requesting administrative access to authorize http server");
  547. try
  548. {
  549. ServerAuthorization.AuthorizeServer(ServerConfigurationManager.Configuration.HttpServerPortNumber,
  550. HttpServerUrlPrefix, ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber,
  551. UdpServerEntryPoint.PortNumber,
  552. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  553. }
  554. catch (Exception ex)
  555. {
  556. Logger.ErrorException("Error authorizing server", ex);
  557. }
  558. }
  559. /// <summary>
  560. /// Checks for update.
  561. /// </summary>
  562. /// <param name="cancellationToken">The cancellation token.</param>
  563. /// <param name="progress">The progress.</param>
  564. /// <returns>Task{CheckForUpdateResult}.</returns>
  565. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  566. {
  567. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  568. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, ApplicationVersion,
  569. ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  570. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  571. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  572. }
  573. /// <summary>
  574. /// Updates the application.
  575. /// </summary>
  576. /// <param name="package">The package that contains the update</param>
  577. /// <param name="cancellationToken">The cancellation token.</param>
  578. /// <param name="progress">The progress.</param>
  579. /// <returns>Task.</returns>
  580. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  581. {
  582. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  583. OnApplicationUpdated(package.version);
  584. }
  585. /// <summary>
  586. /// Creates the HTTP client.
  587. /// </summary>
  588. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  589. /// <returns>HttpClient.</returns>
  590. protected override HttpClient CreateHttpClient(bool enableHttpCompression)
  591. {
  592. return HttpClientFactory.GetHttpClient(enableHttpCompression);
  593. }
  594. protected override void ConfigureAutoRunAtStartup(bool autorun)
  595. {
  596. Autorun.Configure(autorun);
  597. }
  598. }
  599. }