ApplicationHost.cs 27 KB

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