ApplicationHost.cs 27 KB

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