ApplicationHost.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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. internal 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. await ((UserManager) UserManager).Initialize().ConfigureAwait(false);
  252. SetKernelProperties();
  253. }
  254. protected override INetworkManager CreateNetworkManager()
  255. {
  256. return new NetworkManager();
  257. }
  258. protected override IFileSystem CreateFileSystemManager()
  259. {
  260. return FileSystemFactory.CreateFileSystemManager(LogManager);
  261. }
  262. /// <summary>
  263. /// Registers the media encoder.
  264. /// </summary>
  265. /// <returns>Task.</returns>
  266. private async Task RegisterMediaEncoder(IProgress<double> progress)
  267. {
  268. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager).GetFFMpegInfo(progress).ConfigureAwait(false);
  269. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ApplicationPaths, JsonSerializer, info.Path, info.ProbePath, info.Version, FileSystemManager);
  270. RegisterSingleInstance(MediaEncoder);
  271. }
  272. /// <summary>
  273. /// Sets the kernel properties.
  274. /// </summary>
  275. private void SetKernelProperties()
  276. {
  277. new FFMpegManager(MediaEncoder, Logger, ItemRepository, FileSystemManager, ServerConfigurationManager);
  278. LocalizedStrings.StringFiles = GetExports<LocalizedStringData>();
  279. SetStaticProperties();
  280. }
  281. /// <summary>
  282. /// Gets the user repository.
  283. /// </summary>
  284. /// <returns>Task{IUserRepository}.</returns>
  285. private async Task<IUserRepository> GetUserRepository()
  286. {
  287. var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths);
  288. await repo.Initialize().ConfigureAwait(false);
  289. return repo;
  290. }
  291. /// <summary>
  292. /// Configures the repositories.
  293. /// </summary>
  294. /// <returns>Task.</returns>
  295. private async Task ConfigureNotificationsRepository()
  296. {
  297. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths);
  298. await repo.Initialize().ConfigureAwait(false);
  299. NotificationsRepository = repo;
  300. RegisterSingleInstance(NotificationsRepository);
  301. }
  302. /// <summary>
  303. /// Configures the repositories.
  304. /// </summary>
  305. /// <returns>Task.</returns>
  306. private async Task ConfigureDisplayPreferencesRepositories()
  307. {
  308. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  309. }
  310. /// <summary>
  311. /// Configures the item repositories.
  312. /// </summary>
  313. /// <returns>Task.</returns>
  314. private async Task ConfigureItemRepositories()
  315. {
  316. await ItemRepository.Initialize().ConfigureAwait(false);
  317. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  318. }
  319. /// <summary>
  320. /// Configures the user data repositories.
  321. /// </summary>
  322. /// <returns>Task.</returns>
  323. private async Task ConfigureUserDataRepositories()
  324. {
  325. var repo = new SqliteUserDataRepository(ApplicationPaths, LogManager);
  326. await repo.Initialize().ConfigureAwait(false);
  327. ((UserDataManager)UserDataManager).Repository = repo;
  328. }
  329. /// <summary>
  330. /// Dirty hacks
  331. /// </summary>
  332. private void SetStaticProperties()
  333. {
  334. // For now there's no real way to inject these properly
  335. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  336. BaseItem.ConfigurationManager = ServerConfigurationManager;
  337. BaseItem.LibraryManager = LibraryManager;
  338. BaseItem.ProviderManager = ProviderManager;
  339. BaseItem.LocalizationManager = LocalizationManager;
  340. BaseItem.ItemRepository = ItemRepository;
  341. User.XmlSerializer = XmlSerializer;
  342. User.UserManager = UserManager;
  343. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  344. Folder.UserManager = UserManager;
  345. BaseItem.FileSystem = FileSystemManager;
  346. }
  347. /// <summary>
  348. /// Finds the parts.
  349. /// </summary>
  350. protected override void FindParts()
  351. {
  352. if (IsFirstRun)
  353. {
  354. RegisterServerWithAdministratorAccess();
  355. }
  356. base.FindParts();
  357. HttpServer.Init(GetExports<IRestfulService>(false));
  358. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  359. StartServer(true);
  360. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  361. GetExports<IVirtualFolderCreator>(),
  362. GetExports<IItemResolver>(),
  363. GetExports<IIntroProvider>(),
  364. GetExports<IBaseItemComparer>(),
  365. GetExports<ILibraryPrescanTask>(),
  366. GetExports<ILibraryPostScanTask>(),
  367. GetExports<IPeoplePrescanTask>(),
  368. GetExports<IMetadataSaver>());
  369. ProviderManager.AddParts(GetExports<BaseMetadataProvider>(), GetExports<IImageProvider>());
  370. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  371. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  372. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  373. }
  374. /// <summary>
  375. /// Starts the server.
  376. /// </summary>
  377. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  378. private void StartServer(bool retryOnFailure)
  379. {
  380. try
  381. {
  382. ServerManager.Start(HttpServerUrlPrefix, ServerConfigurationManager.Configuration.EnableHttpLevelLogging);
  383. }
  384. catch (Exception ex)
  385. {
  386. Logger.ErrorException("Error starting http server", ex);
  387. if (retryOnFailure)
  388. {
  389. RegisterServerWithAdministratorAccess();
  390. StartServer(false);
  391. }
  392. else
  393. {
  394. throw;
  395. }
  396. }
  397. ServerManager.StartWebSocketServer();
  398. }
  399. /// <summary>
  400. /// Called when [configuration updated].
  401. /// </summary>
  402. /// <param name="sender">The sender.</param>
  403. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  404. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  405. {
  406. base.OnConfigurationUpdated(sender, e);
  407. HttpServer.EnableHttpRequestLogging = ServerConfigurationManager.Configuration.EnableHttpLevelLogging;
  408. if (!string.Equals(HttpServer.UrlPrefix, HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  409. {
  410. NotifyPendingRestart();
  411. }
  412. else if (!ServerManager.SupportsNativeWebSocket && ServerManager.WebSocketPortNumber != ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  413. {
  414. NotifyPendingRestart();
  415. }
  416. }
  417. /// <summary>
  418. /// Restarts this instance.
  419. /// </summary>
  420. public override async Task Restart()
  421. {
  422. if (!CanSelfRestart)
  423. {
  424. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  425. }
  426. try
  427. {
  428. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  429. }
  430. catch (Exception ex)
  431. {
  432. Logger.ErrorException("Error sending server restart notification", ex);
  433. }
  434. NativeApp.Restart();
  435. }
  436. /// <summary>
  437. /// Gets or sets a value indicating whether this instance can self update.
  438. /// </summary>
  439. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  440. public override bool CanSelfUpdate
  441. {
  442. get
  443. {
  444. #if DEBUG
  445. return false;
  446. #endif
  447. return NativeApp.CanSelfUpdate;
  448. }
  449. }
  450. /// <summary>
  451. /// Gets the composable part assemblies.
  452. /// </summary>
  453. /// <returns>IEnumerable{Assembly}.</returns>
  454. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  455. {
  456. var list = GetPluginAssemblies()
  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. /// <summary>
  482. /// Gets the plugin assemblies.
  483. /// </summary>
  484. /// <returns>IEnumerable{Assembly}.</returns>
  485. private IEnumerable<Assembly> GetPluginAssemblies()
  486. {
  487. try
  488. {
  489. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  490. .Select(LoadAssembly)
  491. .Where(a => a != null)
  492. .ToList();
  493. }
  494. catch (DirectoryNotFoundException)
  495. {
  496. return new List<Assembly>();
  497. }
  498. }
  499. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  500. /// <summary>
  501. /// Gets the system status.
  502. /// </summary>
  503. /// <returns>SystemInfo.</returns>
  504. public virtual SystemInfo GetSystemInfo()
  505. {
  506. return new SystemInfo
  507. {
  508. HasPendingRestart = HasPendingRestart,
  509. Version = ApplicationVersion.ToString(),
  510. IsNetworkDeployed = CanSelfUpdate,
  511. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  512. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  513. FailedPluginAssemblies = FailedAssemblies.ToList(),
  514. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  515. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  516. Id = _systemId,
  517. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  518. LogPath = ApplicationPaths.LogDirectoryPath,
  519. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  520. CachePath = ApplicationPaths.CachePath,
  521. MacAddress = GetMacAddress(),
  522. HttpServerPortNumber = ServerConfigurationManager.Configuration.HttpServerPortNumber,
  523. OperatingSystem = Environment.OSVersion.ToString(),
  524. CanSelfRestart = CanSelfRestart,
  525. CanSelfUpdate = CanSelfUpdate,
  526. WanAddress = WanAddressEntryPoint.WanAddress
  527. };
  528. }
  529. /// <summary>
  530. /// Gets the mac address.
  531. /// </summary>
  532. /// <returns>System.String.</returns>
  533. private string GetMacAddress()
  534. {
  535. try
  536. {
  537. return NetworkManager.GetMacAddress();
  538. }
  539. catch (Exception ex)
  540. {
  541. Logger.ErrorException("Error getting mac address", ex);
  542. return null;
  543. }
  544. }
  545. /// <summary>
  546. /// Shuts down.
  547. /// </summary>
  548. public override async Task Shutdown()
  549. {
  550. try
  551. {
  552. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  553. }
  554. catch (Exception ex)
  555. {
  556. Logger.ErrorException("Error sending server shutdown notification", ex);
  557. }
  558. NativeApp.Shutdown();
  559. }
  560. /// <summary>
  561. /// Registers the server with administrator access.
  562. /// </summary>
  563. private void RegisterServerWithAdministratorAccess()
  564. {
  565. Logger.Info("Requesting administrative access to authorize http server");
  566. try
  567. {
  568. ServerAuthorization.AuthorizeServer(ServerConfigurationManager.Configuration.HttpServerPortNumber,
  569. HttpServerUrlPrefix, ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber,
  570. UdpServerEntryPoint.PortNumber,
  571. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  572. }
  573. catch (Exception ex)
  574. {
  575. Logger.ErrorException("Error authorizing server", ex);
  576. }
  577. }
  578. /// <summary>
  579. /// Checks for update.
  580. /// </summary>
  581. /// <param name="cancellationToken">The cancellation token.</param>
  582. /// <param name="progress">The progress.</param>
  583. /// <returns>Task{CheckForUpdateResult}.</returns>
  584. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  585. {
  586. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  587. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, null, ApplicationVersion,
  588. ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  589. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  590. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  591. }
  592. /// <summary>
  593. /// Updates the application.
  594. /// </summary>
  595. /// <param name="package">The package that contains the update</param>
  596. /// <param name="cancellationToken">The cancellation token.</param>
  597. /// <param name="progress">The progress.</param>
  598. /// <returns>Task.</returns>
  599. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  600. {
  601. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  602. OnApplicationUpdated(package.version);
  603. }
  604. protected override void ConfigureAutoRunAtStartup(bool autorun)
  605. {
  606. Autorun.Configure(autorun);
  607. }
  608. }
  609. }