ApplicationHost.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. 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
  391. {
  392. if (retryOnFailure)
  393. {
  394. RegisterServerWithAdministratorAccess();
  395. StartServer(false);
  396. }
  397. else
  398. {
  399. throw;
  400. }
  401. }
  402. ServerManager.StartWebSocketServer();
  403. }
  404. /// <summary>
  405. /// Called when [configuration updated].
  406. /// </summary>
  407. /// <param name="sender">The sender.</param>
  408. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  409. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  410. {
  411. base.OnConfigurationUpdated(sender, e);
  412. HttpServer.EnableHttpRequestLogging = ServerConfigurationManager.Configuration.EnableHttpLevelLogging;
  413. if (!string.Equals(HttpServer.UrlPrefix, HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  414. {
  415. NotifyPendingRestart();
  416. }
  417. else if (!ServerManager.SupportsNativeWebSocket && ServerManager.WebSocketPortNumber != ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  418. {
  419. NotifyPendingRestart();
  420. }
  421. }
  422. /// <summary>
  423. /// Restarts this instance.
  424. /// </summary>
  425. public override async Task Restart()
  426. {
  427. try
  428. {
  429. await ServerManager.SendWebSocketMessageAsync("ServerRestarting", () => string.Empty, CancellationToken.None).ConfigureAwait(false);
  430. }
  431. catch (Exception ex)
  432. {
  433. Logger.ErrorException("Error sending server restart web socket message", 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 ConfigurationManager.CommonConfiguration.EnableAutoUpdate;
  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. };
  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 ServerManager.SendWebSocketMessageAsync("ServerShuttingDown", () => string.Empty, CancellationToken.None).ConfigureAwait(false);
  531. }
  532. catch (Exception ex)
  533. {
  534. Logger.ErrorException("Error sending server shutdown web socket message", 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, ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  566. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  567. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  568. }
  569. /// <summary>
  570. /// Updates the application.
  571. /// </summary>
  572. /// <param name="package">The package that contains the update</param>
  573. /// <param name="cancellationToken">The cancellation token.</param>
  574. /// <param name="progress">The progress.</param>
  575. /// <returns>Task.</returns>
  576. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  577. {
  578. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  579. OnApplicationUpdated(package.version);
  580. }
  581. /// <summary>
  582. /// Gets the HTTP message handler.
  583. /// </summary>
  584. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  585. /// <returns>HttpMessageHandler.</returns>
  586. protected override HttpMessageHandler GetHttpMessageHandler(bool enableHttpCompression)
  587. {
  588. return HttpMessageHandlerFactory.GetHttpMessageHandler(enableHttpCompression);
  589. }
  590. protected override void ConfigureAutoRunAtStartup(bool autorun)
  591. {
  592. Autorun.Configure(autorun);
  593. }
  594. }
  595. }