ApplicationHost.cs 27 KB

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