2
0

ApplicationHost.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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.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.IO;
  28. using MediaBrowser.Model.Logging;
  29. using MediaBrowser.Model.MediaInfo;
  30. using MediaBrowser.Model.System;
  31. using MediaBrowser.Model.Updates;
  32. using MediaBrowser.Providers;
  33. using MediaBrowser.Server.Implementations;
  34. using MediaBrowser.Server.Implementations.BdInfo;
  35. using MediaBrowser.Server.Implementations.Configuration;
  36. using MediaBrowser.Server.Implementations.Drawing;
  37. using MediaBrowser.Server.Implementations.Dto;
  38. using MediaBrowser.Server.Implementations.EntryPoints;
  39. using MediaBrowser.Server.Implementations.HttpServer;
  40. using MediaBrowser.Server.Implementations.IO;
  41. using MediaBrowser.Server.Implementations.Library;
  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.WebDashboard.Api;
  52. using System;
  53. using System.Collections.Generic;
  54. using System.Data;
  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 IIsoManager IsoManager { get; set; }
  147. private ISessionManager SessionManager { 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 IUserDataRepository UserDataRepository { 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. /// Runs the startup tasks.
  170. /// </summary>
  171. /// <returns>Task.</returns>
  172. public override async Task RunStartupTasks()
  173. {
  174. await base.RunStartupTasks().ConfigureAwait(false);
  175. DirectoryWatchers.Start();
  176. Logger.Info("Core startup complete");
  177. Parallel.ForEach(GetExports<IServerEntryPoint>(), entryPoint =>
  178. {
  179. try
  180. {
  181. entryPoint.Run();
  182. }
  183. catch (Exception ex)
  184. {
  185. Logger.ErrorException("Error in {0}", ex, entryPoint.GetType().Name);
  186. }
  187. });
  188. }
  189. /// <summary>
  190. /// Called when [logger loaded].
  191. /// </summary>
  192. protected override void OnLoggerLoaded()
  193. {
  194. base.OnLoggerLoaded();
  195. _httpServerCreationTask = Task.Run(() => ServerFactory.CreateServer(this, LogManager, "Media Browser", "dashboard/index.html"));
  196. }
  197. /// <summary>
  198. /// Registers resources that classes will depend on
  199. /// </summary>
  200. /// <returns>Task.</returns>
  201. protected override async Task RegisterResources()
  202. {
  203. ServerKernel = new Kernel();
  204. await base.RegisterResources().ConfigureAwait(false);
  205. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager));
  206. RegisterSingleInstance<IServerApplicationHost>(this);
  207. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  208. RegisterSingleInstance(ServerKernel);
  209. RegisterSingleInstance(ServerConfigurationManager);
  210. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  211. IsoManager = new IsoManager();
  212. RegisterSingleInstance(IsoManager);
  213. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  214. var mediaEncoderTask = RegisterMediaEncoder();
  215. UserDataRepository = new SqliteUserDataRepository(ApplicationPaths, JsonSerializer, LogManager);
  216. RegisterSingleInstance(UserDataRepository);
  217. UserRepository = await GetUserRepository().ConfigureAwait(false);
  218. RegisterSingleInstance(UserRepository);
  219. DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
  220. RegisterSingleInstance(DisplayPreferencesRepository);
  221. ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
  222. RegisterSingleInstance(ItemRepository);
  223. UserManager = new UserManager(Logger, ServerConfigurationManager, UserRepository);
  224. RegisterSingleInstance(UserManager);
  225. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataRepository, () => DirectoryWatchers);
  226. RegisterSingleInstance(LibraryManager);
  227. DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager);
  228. RegisterSingleInstance(DirectoryWatchers);
  229. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager, LibraryManager);
  230. RegisterSingleInstance(ProviderManager);
  231. RegisterSingleInstance<ILibrarySearchEngine>(() => new LuceneSearchEngine(ApplicationPaths, LogManager, LibraryManager));
  232. SessionManager = new SessionManager(UserDataRepository, ServerConfigurationManager, Logger, UserRepository);
  233. RegisterSingleInstance<ISessionManager>(SessionManager);
  234. HttpServer = await _httpServerCreationTask.ConfigureAwait(false);
  235. RegisterSingleInstance(HttpServer, false);
  236. ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager);
  237. RegisterSingleInstance(ServerManager);
  238. LocalizationManager = new LocalizationManager(ServerConfigurationManager);
  239. RegisterSingleInstance(LocalizationManager);
  240. ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths);
  241. RegisterSingleInstance(ImageProcessor);
  242. DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataRepository, ItemRepository, ImageProcessor);
  243. RegisterSingleInstance(DtoService);
  244. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  245. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  246. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  247. await ConfigureNotificationsRepository().ConfigureAwait(false);
  248. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask, mediaEncoderTask).ConfigureAwait(false);
  249. SetKernelProperties();
  250. }
  251. /// <summary>
  252. /// Registers the media encoder.
  253. /// </summary>
  254. /// <returns>Task.</returns>
  255. private async Task RegisterMediaEncoder()
  256. {
  257. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient).GetFFMpegInfo().ConfigureAwait(false);
  258. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ApplicationPaths, JsonSerializer, info.Path, info.ProbePath, info.Version);
  259. RegisterSingleInstance(MediaEncoder);
  260. }
  261. /// <summary>
  262. /// Sets the kernel properties.
  263. /// </summary>
  264. private void SetKernelProperties()
  265. {
  266. Parallel.Invoke(
  267. () => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, Logger, ItemRepository),
  268. () => LocalizedStrings.StringFiles = GetExports<LocalizedStringData>(),
  269. SetStaticProperties
  270. );
  271. }
  272. private async Task<IUserRepository> GetUserRepository()
  273. {
  274. var dbFile = Path.Combine(ApplicationPaths.DataPath, "users.db");
  275. var connection = await ConnectToDb(dbFile).ConfigureAwait(false);
  276. var repo = new SqliteUserRepository(connection, JsonSerializer, LogManager);
  277. repo.Initialize();
  278. return repo;
  279. }
  280. /// <summary>
  281. /// Configures the repositories.
  282. /// </summary>
  283. /// <returns>Task.</returns>
  284. private async Task ConfigureNotificationsRepository()
  285. {
  286. var dbFile = Path.Combine(ApplicationPaths.DataPath, "notifications.db");
  287. var connection = await ConnectToDb(dbFile).ConfigureAwait(false);
  288. var repo = new SqliteNotificationsRepository(connection, LogManager);
  289. repo.Initialize();
  290. NotificationsRepository = repo;
  291. RegisterSingleInstance(NotificationsRepository);
  292. }
  293. /// <summary>
  294. /// Configures the repositories.
  295. /// </summary>
  296. /// <returns>Task.</returns>
  297. private async Task ConfigureDisplayPreferencesRepositories()
  298. {
  299. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  300. }
  301. /// <summary>
  302. /// Configures the item repositories.
  303. /// </summary>
  304. /// <returns>Task.</returns>
  305. private async Task ConfigureItemRepositories()
  306. {
  307. await ItemRepository.Initialize().ConfigureAwait(false);
  308. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  309. }
  310. /// <summary>
  311. /// Configures the user data repositories.
  312. /// </summary>
  313. /// <returns>Task.</returns>
  314. private Task ConfigureUserDataRepositories()
  315. {
  316. return UserDataRepository.Initialize();
  317. }
  318. /// <summary>
  319. /// Connects to db.
  320. /// </summary>
  321. /// <param name="dbPath">The db path.</param>
  322. /// <returns>Task{IDbConnection}.</returns>
  323. /// <exception cref="System.ArgumentNullException">dbPath</exception>
  324. private static Task<IDbConnection> ConnectToDb(string dbPath)
  325. {
  326. if (string.IsNullOrEmpty(dbPath))
  327. {
  328. throw new ArgumentNullException("dbPath");
  329. }
  330. return Sqlite.OpenDatabase(dbPath);
  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. }
  348. /// <summary>
  349. /// Finds the parts.
  350. /// </summary>
  351. protected override void FindParts()
  352. {
  353. if (IsFirstRun)
  354. {
  355. RegisterServerWithAdministratorAccess();
  356. }
  357. base.FindParts();
  358. HttpServer.Init(GetExports<IRestfulService>(false));
  359. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  360. StartServer(true);
  361. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  362. GetExports<IVirtualFolderCreator>(),
  363. GetExports<IItemResolver>(),
  364. GetExports<IIntroProvider>(),
  365. GetExports<IBaseItemComparer>(),
  366. GetExports<ILibraryPrescanTask>(),
  367. GetExports<ILibraryPostScanTask>(),
  368. GetExports<IMetadataSaver>());
  369. ProviderManager.AddParts(GetExports<BaseMetadataProvider>());
  370. IsoManager.AddParts(GetExports<IIsoMounter>());
  371. SessionManager.AddParts(GetExports<ISessionRemoteController>());
  372. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  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. try
  422. {
  423. await ServerManager.SendWebSocketMessageAsync("ServerRestarting", () => string.Empty, CancellationToken.None).ConfigureAwait(false);
  424. }
  425. catch (Exception ex)
  426. {
  427. Logger.ErrorException("Error sending server restart web socket message", ex);
  428. }
  429. NativeApp.Restart();
  430. }
  431. /// <summary>
  432. /// Gets or sets a value indicating whether this instance can self update.
  433. /// </summary>
  434. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  435. public override bool CanSelfUpdate
  436. {
  437. get
  438. {
  439. #if DEBUG
  440. return false;
  441. #endif
  442. return ConfigurationManager.CommonConfiguration.EnableAutoUpdate;
  443. }
  444. }
  445. /// <summary>
  446. /// Gets the composable part assemblies.
  447. /// </summary>
  448. /// <returns>IEnumerable{Assembly}.</returns>
  449. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  450. {
  451. var list = Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  452. .Select(LoadAssembly)
  453. .Where(a => a != null)
  454. .ToList();
  455. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  456. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  457. // Include composable parts in the Api assembly
  458. list.Add(typeof(ApiEntryPoint).Assembly);
  459. // Include composable parts in the Dashboard assembly
  460. list.Add(typeof(DashboardInfo).Assembly);
  461. // Include composable parts in the Model assembly
  462. list.Add(typeof(SystemInfo).Assembly);
  463. // Include composable parts in the Common assembly
  464. list.Add(typeof(IApplicationHost).Assembly);
  465. // Include composable parts in the Controller assembly
  466. list.Add(typeof(Kernel).Assembly);
  467. // Include composable parts in the Providers assembly
  468. list.Add(typeof(ImagesByNameProvider).Assembly);
  469. // Common implementations
  470. list.Add(typeof(TaskManager).Assembly);
  471. // Server implementations
  472. list.Add(typeof(ServerApplicationPaths).Assembly);
  473. list.AddRange(Assemblies.GetAssembliesWithParts());
  474. // Include composable parts in the running assembly
  475. list.Add(GetType().Assembly);
  476. return list;
  477. }
  478. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  479. /// <summary>
  480. /// Gets the system status.
  481. /// </summary>
  482. /// <returns>SystemInfo.</returns>
  483. public virtual SystemInfo GetSystemInfo()
  484. {
  485. return new SystemInfo
  486. {
  487. HasPendingRestart = HasPendingRestart,
  488. Version = ApplicationVersion.ToString(),
  489. IsNetworkDeployed = CanSelfUpdate,
  490. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  491. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  492. FailedPluginAssemblies = FailedAssemblies.ToList(),
  493. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  494. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  495. Id = _systemId,
  496. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  497. MacAddress = GetMacAddress(),
  498. HttpServerPortNumber = ServerConfigurationManager.Configuration.HttpServerPortNumber
  499. };
  500. }
  501. /// <summary>
  502. /// Gets the mac address.
  503. /// </summary>
  504. /// <returns>System.String.</returns>
  505. private string GetMacAddress()
  506. {
  507. try
  508. {
  509. return NetworkManager.GetMacAddress();
  510. }
  511. catch (Exception ex)
  512. {
  513. Logger.ErrorException("Error getting mac address", ex);
  514. return null;
  515. }
  516. }
  517. /// <summary>
  518. /// Shuts down.
  519. /// </summary>
  520. public override async Task Shutdown()
  521. {
  522. try
  523. {
  524. await ServerManager.SendWebSocketMessageAsync("ServerShuttingDown", () => string.Empty, CancellationToken.None).ConfigureAwait(false);
  525. }
  526. catch (Exception ex)
  527. {
  528. Logger.ErrorException("Error sending server shutdown web socket message", ex);
  529. }
  530. NativeApp.Shutdown();
  531. }
  532. /// <summary>
  533. /// Registers the server with administrator access.
  534. /// </summary>
  535. private void RegisterServerWithAdministratorAccess()
  536. {
  537. Logger.Info("Requesting administrative access to authorize http server");
  538. try
  539. {
  540. ServerAuthorization.AuthorizeServer(ServerConfigurationManager.Configuration.HttpServerPortNumber,
  541. HttpServerUrlPrefix, ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber,
  542. UdpServerEntryPoint.PortNumber,
  543. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  544. }
  545. catch (Exception ex)
  546. {
  547. Logger.ErrorException("Error authorizing server", ex);
  548. }
  549. }
  550. /// <summary>
  551. /// Checks for update.
  552. /// </summary>
  553. /// <param name="cancellationToken">The cancellation token.</param>
  554. /// <param name="progress">The progress.</param>
  555. /// <returns>Task{CheckForUpdateResult}.</returns>
  556. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  557. {
  558. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  559. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, ApplicationVersion, ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  560. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  561. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  562. }
  563. /// <summary>
  564. /// Updates the application.
  565. /// </summary>
  566. /// <param name="package">The package that contains the update</param>
  567. /// <param name="cancellationToken">The cancellation token.</param>
  568. /// <param name="progress">The progress.</param>
  569. /// <returns>Task.</returns>
  570. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  571. {
  572. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  573. OnApplicationUpdated(package.version);
  574. }
  575. /// <summary>
  576. /// Gets the HTTP message handler.
  577. /// </summary>
  578. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  579. /// <returns>HttpMessageHandler.</returns>
  580. protected override HttpMessageHandler GetHttpMessageHandler(bool enableHttpCompression)
  581. {
  582. return HttpMessageHandlerFactory.GetHttpMessageHandler(enableHttpCompression);
  583. }
  584. protected override void ConfigureAutoRunAtStartup(bool autorun)
  585. {
  586. Autorun.Configure(autorun);
  587. }
  588. }
  589. }