ApplicationHost.cs 27 KB

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