ApplicationHost.cs 27 KB

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