ApplicationHost.cs 28 KB

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