2
0

ApplicationHost.cs 28 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.Common.Progress;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Controller.Configuration;
  14. using MediaBrowser.Controller.Drawing;
  15. using MediaBrowser.Controller.Dto;
  16. using MediaBrowser.Controller.Entities;
  17. using MediaBrowser.Controller.IO;
  18. using MediaBrowser.Controller.Library;
  19. using MediaBrowser.Controller.LiveTv;
  20. using MediaBrowser.Controller.Localization;
  21. using MediaBrowser.Controller.MediaInfo;
  22. using MediaBrowser.Controller.Net;
  23. using MediaBrowser.Controller.Notifications;
  24. using MediaBrowser.Controller.Persistence;
  25. using MediaBrowser.Controller.Plugins;
  26. using MediaBrowser.Controller.Providers;
  27. using MediaBrowser.Controller.Resolvers;
  28. using MediaBrowser.Controller.Session;
  29. using MediaBrowser.Controller.Sorting;
  30. using MediaBrowser.Model.Logging;
  31. using MediaBrowser.Model.MediaInfo;
  32. using MediaBrowser.Model.System;
  33. using MediaBrowser.Model.Updates;
  34. using MediaBrowser.Providers;
  35. using MediaBrowser.Server.Implementations;
  36. using MediaBrowser.Server.Implementations.BdInfo;
  37. using MediaBrowser.Server.Implementations.Configuration;
  38. using MediaBrowser.Server.Implementations.Drawing;
  39. using MediaBrowser.Server.Implementations.Dto;
  40. using MediaBrowser.Server.Implementations.EntryPoints;
  41. using MediaBrowser.Server.Implementations.HttpServer;
  42. using MediaBrowser.Server.Implementations.IO;
  43. using MediaBrowser.Server.Implementations.Library;
  44. using MediaBrowser.Server.Implementations.LiveTv;
  45. using MediaBrowser.Server.Implementations.Localization;
  46. using MediaBrowser.Server.Implementations.MediaEncoder;
  47. using MediaBrowser.Server.Implementations.Persistence;
  48. using MediaBrowser.Server.Implementations.Providers;
  49. using MediaBrowser.Server.Implementations.ServerManager;
  50. using MediaBrowser.Server.Implementations.Session;
  51. using MediaBrowser.Server.Implementations.WebSocket;
  52. using MediaBrowser.ServerApplication.EntryPoints;
  53. using MediaBrowser.ServerApplication.FFMpeg;
  54. using MediaBrowser.ServerApplication.IO;
  55. using MediaBrowser.ServerApplication.Native;
  56. using MediaBrowser.ServerApplication.Networking;
  57. using MediaBrowser.WebDashboard.Api;
  58. using System;
  59. using System.Collections.Generic;
  60. using System.IO;
  61. using System.Linq;
  62. using System.Reflection;
  63. using System.Threading;
  64. using System.Threading.Tasks;
  65. namespace MediaBrowser.ServerApplication
  66. {
  67. /// <summary>
  68. /// Class CompositionRoot
  69. /// </summary>
  70. public class ApplicationHost : BaseApplicationHost<ServerApplicationPaths>, IServerApplicationHost
  71. {
  72. /// <summary>
  73. /// Gets the server kernel.
  74. /// </summary>
  75. /// <value>The server kernel.</value>
  76. protected Kernel ServerKernel { get; set; }
  77. /// <summary>
  78. /// Gets the server configuration manager.
  79. /// </summary>
  80. /// <value>The server configuration manager.</value>
  81. public IServerConfigurationManager ServerConfigurationManager
  82. {
  83. get { return (IServerConfigurationManager)ConfigurationManager; }
  84. }
  85. /// <summary>
  86. /// Gets the name of the web application that can be used for url building.
  87. /// All api urls will be of the form {protocol}://{host}:{port}/{appname}/...
  88. /// </summary>
  89. /// <value>The name of the web application.</value>
  90. public string WebApplicationName
  91. {
  92. get { return "mediabrowser"; }
  93. }
  94. /// <summary>
  95. /// Gets the HTTP server URL prefix.
  96. /// </summary>
  97. /// <value>The HTTP server URL prefix.</value>
  98. public string HttpServerUrlPrefix
  99. {
  100. get
  101. {
  102. return "http://+:" + ServerConfigurationManager.Configuration.HttpServerPortNumber + "/" + WebApplicationName + "/";
  103. }
  104. }
  105. /// <summary>
  106. /// Gets the configuration manager.
  107. /// </summary>
  108. /// <returns>IConfigurationManager.</returns>
  109. protected override IConfigurationManager GetConfigurationManager()
  110. {
  111. return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer);
  112. }
  113. /// <summary>
  114. /// Gets or sets the server manager.
  115. /// </summary>
  116. /// <value>The server manager.</value>
  117. private IServerManager ServerManager { get; set; }
  118. /// <summary>
  119. /// Gets or sets the user manager.
  120. /// </summary>
  121. /// <value>The user manager.</value>
  122. public IUserManager UserManager { get; set; }
  123. /// <summary>
  124. /// Gets or sets the library manager.
  125. /// </summary>
  126. /// <value>The library manager.</value>
  127. internal ILibraryManager LibraryManager { get; set; }
  128. /// <summary>
  129. /// Gets or sets the directory watchers.
  130. /// </summary>
  131. /// <value>The directory watchers.</value>
  132. private IDirectoryWatchers DirectoryWatchers { get; set; }
  133. /// <summary>
  134. /// Gets or sets the provider manager.
  135. /// </summary>
  136. /// <value>The provider manager.</value>
  137. private IProviderManager ProviderManager { get; set; }
  138. /// <summary>
  139. /// Gets or sets the HTTP server.
  140. /// </summary>
  141. /// <value>The HTTP server.</value>
  142. private IHttpServer HttpServer { get; set; }
  143. private IDtoService DtoService { get; set; }
  144. private IImageProcessor ImageProcessor { get; set; }
  145. /// <summary>
  146. /// Gets or sets the media encoder.
  147. /// </summary>
  148. /// <value>The media encoder.</value>
  149. private IMediaEncoder MediaEncoder { get; set; }
  150. private ISessionManager SessionManager { get; set; }
  151. private ILiveTvManager LiveTvManager { get; set; }
  152. private ILocalizationManager LocalizationManager { get; set; }
  153. /// <summary>
  154. /// Gets or sets the user data repository.
  155. /// </summary>
  156. /// <value>The user data repository.</value>
  157. private IUserDataManager UserDataManager { get; set; }
  158. private IUserRepository UserRepository { get; set; }
  159. internal IDisplayPreferencesRepository DisplayPreferencesRepository { get; set; }
  160. private IItemRepository ItemRepository { get; set; }
  161. private INotificationsRepository NotificationsRepository { get; set; }
  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. /// Registers resources that classes will depend on
  201. /// </summary>
  202. /// <returns>Task.</returns>
  203. protected override async Task RegisterResources(IProgress<double> progress)
  204. {
  205. ServerKernel = new Kernel();
  206. await base.RegisterResources(progress).ConfigureAwait(false);
  207. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager));
  208. RegisterSingleInstance<IServerApplicationHost>(this);
  209. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  210. RegisterSingleInstance(ServerKernel);
  211. RegisterSingleInstance(ServerConfigurationManager);
  212. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  213. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  214. UserDataManager = new UserDataManager(LogManager);
  215. RegisterSingleInstance(UserDataManager);
  216. UserRepository = await GetUserRepository().ConfigureAwait(false);
  217. RegisterSingleInstance(UserRepository);
  218. DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
  219. RegisterSingleInstance(DisplayPreferencesRepository);
  220. ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
  221. RegisterSingleInstance(ItemRepository);
  222. UserManager = new UserManager(Logger, ServerConfigurationManager, UserRepository);
  223. RegisterSingleInstance(UserManager);
  224. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => DirectoryWatchers, FileSystemManager);
  225. RegisterSingleInstance(LibraryManager);
  226. DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
  227. RegisterSingleInstance(DirectoryWatchers);
  228. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager, FileSystemManager, ItemRepository);
  229. RegisterSingleInstance(ProviderManager);
  230. RegisterSingleInstance<ILibrarySearchEngine>(() => new LuceneSearchEngine(ApplicationPaths, LogManager, LibraryManager));
  231. SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager);
  232. RegisterSingleInstance(SessionManager);
  233. HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", "mediabrowser", "dashboard/index.html");
  234. RegisterSingleInstance(HttpServer, false);
  235. progress.Report(10);
  236. ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager);
  237. RegisterSingleInstance(ServerManager);
  238. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager);
  239. RegisterSingleInstance(LocalizationManager);
  240. ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer);
  241. RegisterSingleInstance(ImageProcessor);
  242. DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataManager, ItemRepository, ImageProcessor);
  243. RegisterSingleInstance(DtoService);
  244. LiveTvManager = new LiveTvManager(ApplicationPaths, FileSystemManager, Logger, ItemRepository, ImageProcessor, LocalizationManager, UserDataManager, DtoService, UserManager);
  245. RegisterSingleInstance(LiveTvManager);
  246. progress.Report(15);
  247. var innerProgress = new ActionableProgress<double>();
  248. innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));
  249. await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);
  250. progress.Report(90);
  251. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  252. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  253. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  254. await ConfigureNotificationsRepository().ConfigureAwait(false);
  255. progress.Report(92);
  256. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);
  257. progress.Report(100);
  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(IProgress<double> progress)
  273. {
  274. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager).GetFFMpegInfo(progress).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, 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. CachePath = ApplicationPaths.CachePath,
  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. }