ApplicationHost.cs 27 KB

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