2
0

ApplicationHost.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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.Globalization;
  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. public bool SupportsAutoRunAtStartup
  176. {
  177. get { return NativeApp.SupportsAutoRunAtStartup; }
  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. await base.RegisterResources(progress).ConfigureAwait(false);
  206. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager));
  207. RegisterSingleInstance<IServerApplicationHost>(this);
  208. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  209. RegisterSingleInstance(ServerConfigurationManager);
  210. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  211. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  212. UserDataManager = new UserDataManager(LogManager);
  213. RegisterSingleInstance(UserDataManager);
  214. UserRepository = await GetUserRepository().ConfigureAwait(false);
  215. RegisterSingleInstance(UserRepository);
  216. DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
  217. RegisterSingleInstance(DisplayPreferencesRepository);
  218. ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
  219. RegisterSingleInstance(ItemRepository);
  220. UserManager = new UserManager(Logger, ServerConfigurationManager, UserRepository);
  221. RegisterSingleInstance(UserManager);
  222. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => DirectoryWatchers, FileSystemManager);
  223. RegisterSingleInstance(LibraryManager);
  224. DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
  225. RegisterSingleInstance(DirectoryWatchers);
  226. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager, FileSystemManager, ItemRepository);
  227. RegisterSingleInstance(ProviderManager);
  228. RegisterSingleInstance<ISearchEngine>(() => new LuceneSearchEngine(ApplicationPaths, LogManager, LibraryManager));
  229. SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager, UserManager);
  230. RegisterSingleInstance(SessionManager);
  231. HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", "mediabrowser", "dashboard/index.html");
  232. RegisterSingleInstance(HttpServer, false);
  233. progress.Report(10);
  234. ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager);
  235. RegisterSingleInstance(ServerManager);
  236. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager);
  237. RegisterSingleInstance(LocalizationManager);
  238. ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer);
  239. RegisterSingleInstance(ImageProcessor);
  240. DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataManager, ItemRepository, ImageProcessor);
  241. RegisterSingleInstance(DtoService);
  242. LiveTvManager = new LiveTvManager(ApplicationPaths, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager);
  243. RegisterSingleInstance(LiveTvManager);
  244. progress.Report(15);
  245. var innerProgress = new ActionableProgress<double>();
  246. innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));
  247. await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);
  248. progress.Report(90);
  249. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  250. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  251. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  252. await ConfigureNotificationsRepository().ConfigureAwait(false);
  253. progress.Report(92);
  254. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);
  255. progress.Report(100);
  256. await ((UserManager)UserManager).Initialize().ConfigureAwait(false);
  257. SetKernelProperties();
  258. }
  259. protected override INetworkManager CreateNetworkManager()
  260. {
  261. return new NetworkManager();
  262. }
  263. protected override IFileSystem CreateFileSystemManager()
  264. {
  265. return FileSystemFactory.CreateFileSystemManager(LogManager);
  266. }
  267. /// <summary>
  268. /// Registers the media encoder.
  269. /// </summary>
  270. /// <returns>Task.</returns>
  271. private async Task RegisterMediaEncoder(IProgress<double> progress)
  272. {
  273. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager).GetFFMpegInfo(progress).ConfigureAwait(false);
  274. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ApplicationPaths, JsonSerializer, info.Path, info.ProbePath, info.Version, FileSystemManager);
  275. RegisterSingleInstance(MediaEncoder);
  276. }
  277. /// <summary>
  278. /// Sets the kernel properties.
  279. /// </summary>
  280. private void SetKernelProperties()
  281. {
  282. new FFMpegManager(MediaEncoder, Logger, ItemRepository, FileSystemManager, ServerConfigurationManager);
  283. LocalizedStrings.StringFiles = GetExports<LocalizedStringData>();
  284. SetStaticProperties();
  285. }
  286. /// <summary>
  287. /// Gets the user repository.
  288. /// </summary>
  289. /// <returns>Task{IUserRepository}.</returns>
  290. private async Task<IUserRepository> GetUserRepository()
  291. {
  292. var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths);
  293. await repo.Initialize().ConfigureAwait(false);
  294. return repo;
  295. }
  296. /// <summary>
  297. /// Configures the repositories.
  298. /// </summary>
  299. /// <returns>Task.</returns>
  300. private async Task ConfigureNotificationsRepository()
  301. {
  302. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths);
  303. await repo.Initialize().ConfigureAwait(false);
  304. NotificationsRepository = repo;
  305. RegisterSingleInstance(NotificationsRepository);
  306. }
  307. /// <summary>
  308. /// Configures the repositories.
  309. /// </summary>
  310. /// <returns>Task.</returns>
  311. private async Task ConfigureDisplayPreferencesRepositories()
  312. {
  313. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  314. }
  315. /// <summary>
  316. /// Configures the item repositories.
  317. /// </summary>
  318. /// <returns>Task.</returns>
  319. private async Task ConfigureItemRepositories()
  320. {
  321. await ItemRepository.Initialize().ConfigureAwait(false);
  322. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  323. }
  324. /// <summary>
  325. /// Configures the user data repositories.
  326. /// </summary>
  327. /// <returns>Task.</returns>
  328. private async Task ConfigureUserDataRepositories()
  329. {
  330. var repo = new SqliteUserDataRepository(ApplicationPaths, LogManager);
  331. await repo.Initialize().ConfigureAwait(false);
  332. ((UserDataManager)UserDataManager).Repository = repo;
  333. }
  334. /// <summary>
  335. /// Dirty hacks
  336. /// </summary>
  337. private void SetStaticProperties()
  338. {
  339. // For now there's no real way to inject these properly
  340. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  341. BaseItem.ConfigurationManager = ServerConfigurationManager;
  342. BaseItem.LibraryManager = LibraryManager;
  343. BaseItem.ProviderManager = ProviderManager;
  344. BaseItem.LocalizationManager = LocalizationManager;
  345. BaseItem.ItemRepository = ItemRepository;
  346. User.XmlSerializer = XmlSerializer;
  347. User.UserManager = UserManager;
  348. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  349. Folder.UserManager = UserManager;
  350. BaseItem.FileSystem = FileSystemManager;
  351. }
  352. /// <summary>
  353. /// Finds the parts.
  354. /// </summary>
  355. protected override void FindParts()
  356. {
  357. if (IsFirstRun)
  358. {
  359. RegisterServerWithAdministratorAccess();
  360. }
  361. base.FindParts();
  362. HttpServer.Init(GetExports<IRestfulService>(false));
  363. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  364. StartServer(true);
  365. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  366. GetExports<IVirtualFolderCreator>(),
  367. GetExports<IItemResolver>(),
  368. GetExports<IIntroProvider>(),
  369. GetExports<IBaseItemComparer>(),
  370. GetExports<ILibraryPrescanTask>(),
  371. GetExports<ILibraryPostScanTask>(),
  372. GetExports<IPeoplePrescanTask>(),
  373. GetExports<IMetadataSaver>());
  374. ProviderManager.AddParts(GetExports<BaseMetadataProvider>(), GetExports<IImageProvider>());
  375. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  376. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  377. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  378. }
  379. /// <summary>
  380. /// Starts the server.
  381. /// </summary>
  382. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  383. private void StartServer(bool retryOnFailure)
  384. {
  385. try
  386. {
  387. ServerManager.Start(HttpServerUrlPrefix, ServerConfigurationManager.Configuration.EnableHttpLevelLogging);
  388. }
  389. catch (Exception ex)
  390. {
  391. Logger.ErrorException("Error starting http server", ex);
  392. if (retryOnFailure)
  393. {
  394. RegisterServerWithAdministratorAccess();
  395. StartServer(false);
  396. }
  397. else
  398. {
  399. throw;
  400. }
  401. }
  402. ServerManager.StartWebSocketServer();
  403. }
  404. /// <summary>
  405. /// Called when [configuration updated].
  406. /// </summary>
  407. /// <param name="sender">The sender.</param>
  408. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  409. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  410. {
  411. base.OnConfigurationUpdated(sender, e);
  412. HttpServer.EnableHttpRequestLogging = ServerConfigurationManager.Configuration.EnableHttpLevelLogging;
  413. if (!string.Equals(HttpServer.UrlPrefix, HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  414. {
  415. NotifyPendingRestart();
  416. }
  417. else if (!ServerManager.SupportsNativeWebSocket && ServerManager.WebSocketPortNumber != ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  418. {
  419. NotifyPendingRestart();
  420. }
  421. }
  422. /// <summary>
  423. /// Restarts this instance.
  424. /// </summary>
  425. public override async Task Restart()
  426. {
  427. if (!CanSelfRestart)
  428. {
  429. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  430. }
  431. try
  432. {
  433. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  434. }
  435. catch (Exception ex)
  436. {
  437. Logger.ErrorException("Error sending server restart notification", ex);
  438. }
  439. NativeApp.Restart();
  440. }
  441. /// <summary>
  442. /// Gets or sets a value indicating whether this instance can self update.
  443. /// </summary>
  444. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  445. public override bool CanSelfUpdate
  446. {
  447. get
  448. {
  449. #if DEBUG
  450. return false;
  451. #endif
  452. return NativeApp.CanSelfUpdate;
  453. }
  454. }
  455. /// <summary>
  456. /// Gets the composable part assemblies.
  457. /// </summary>
  458. /// <returns>IEnumerable{Assembly}.</returns>
  459. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  460. {
  461. var list = GetPluginAssemblies()
  462. .ToList();
  463. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  464. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  465. // Include composable parts in the Api assembly
  466. list.Add(typeof(ApiEntryPoint).Assembly);
  467. // Include composable parts in the Dashboard assembly
  468. list.Add(typeof(DashboardInfo).Assembly);
  469. // Include composable parts in the Model assembly
  470. list.Add(typeof(SystemInfo).Assembly);
  471. // Include composable parts in the Common assembly
  472. list.Add(typeof(IApplicationHost).Assembly);
  473. // Include composable parts in the Controller assembly
  474. list.Add(typeof(IServerApplicationHost).Assembly);
  475. // Include composable parts in the Providers assembly
  476. list.Add(typeof(ImagesByNameProvider).Assembly);
  477. // Common implementations
  478. list.Add(typeof(TaskManager).Assembly);
  479. // Server implementations
  480. list.Add(typeof(ServerApplicationPaths).Assembly);
  481. list.AddRange(Assemblies.GetAssembliesWithParts());
  482. // Include composable parts in the running assembly
  483. list.Add(GetType().Assembly);
  484. return list;
  485. }
  486. /// <summary>
  487. /// Gets the plugin assemblies.
  488. /// </summary>
  489. /// <returns>IEnumerable{Assembly}.</returns>
  490. private IEnumerable<Assembly> GetPluginAssemblies()
  491. {
  492. try
  493. {
  494. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  495. .Select(LoadAssembly)
  496. .Where(a => a != null)
  497. .ToList();
  498. }
  499. catch (DirectoryNotFoundException)
  500. {
  501. return new List<Assembly>();
  502. }
  503. }
  504. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  505. /// <summary>
  506. /// Gets the system status.
  507. /// </summary>
  508. /// <returns>SystemInfo.</returns>
  509. public virtual SystemInfo GetSystemInfo()
  510. {
  511. return new SystemInfo
  512. {
  513. HasPendingRestart = HasPendingRestart,
  514. Version = ApplicationVersion.ToString(),
  515. IsNetworkDeployed = CanSelfUpdate,
  516. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  517. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  518. FailedPluginAssemblies = FailedAssemblies.ToList(),
  519. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  520. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  521. Id = _systemId,
  522. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  523. LogPath = ApplicationPaths.LogDirectoryPath,
  524. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  525. CachePath = ApplicationPaths.CachePath,
  526. MacAddress = GetMacAddress(),
  527. HttpServerPortNumber = ServerConfigurationManager.Configuration.HttpServerPortNumber,
  528. OperatingSystem = Environment.OSVersion.ToString(),
  529. CanSelfRestart = CanSelfRestart,
  530. CanSelfUpdate = CanSelfUpdate,
  531. WanAddress = GetWanAddress(),
  532. HasUpdateAvailable = _hasUpdateAvailable,
  533. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup
  534. };
  535. }
  536. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  537. private string GetWanAddress()
  538. {
  539. var ip = WanAddressEntryPoint.WanAddress;
  540. if (!string.IsNullOrEmpty(ip))
  541. {
  542. return "http://" + ip + ":" + ServerConfigurationManager.Configuration.HttpServerPortNumber.ToString(_usCulture);
  543. }
  544. return null;
  545. }
  546. /// <summary>
  547. /// Gets the mac address.
  548. /// </summary>
  549. /// <returns>System.String.</returns>
  550. private string GetMacAddress()
  551. {
  552. try
  553. {
  554. return NetworkManager.GetMacAddress();
  555. }
  556. catch (Exception ex)
  557. {
  558. Logger.ErrorException("Error getting mac address", ex);
  559. return null;
  560. }
  561. }
  562. /// <summary>
  563. /// Shuts down.
  564. /// </summary>
  565. public override async Task Shutdown()
  566. {
  567. try
  568. {
  569. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  570. }
  571. catch (Exception ex)
  572. {
  573. Logger.ErrorException("Error sending server shutdown notification", ex);
  574. }
  575. NativeApp.Shutdown();
  576. }
  577. /// <summary>
  578. /// Registers the server with administrator access.
  579. /// </summary>
  580. private void RegisterServerWithAdministratorAccess()
  581. {
  582. Logger.Info("Requesting administrative access to authorize http server");
  583. try
  584. {
  585. ServerAuthorization.AuthorizeServer(ServerConfigurationManager.Configuration.HttpServerPortNumber,
  586. HttpServerUrlPrefix, ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber,
  587. UdpServerEntryPoint.PortNumber,
  588. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  589. }
  590. catch (Exception ex)
  591. {
  592. Logger.ErrorException("Error authorizing server", ex);
  593. }
  594. }
  595. private bool _hasUpdateAvailable;
  596. /// <summary>
  597. /// Checks for update.
  598. /// </summary>
  599. /// <param name="cancellationToken">The cancellation token.</param>
  600. /// <param name="progress">The progress.</param>
  601. /// <returns>Task{CheckForUpdateResult}.</returns>
  602. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  603. {
  604. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  605. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, null, ApplicationVersion,
  606. ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  607. _hasUpdateAvailable = version != null;
  608. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  609. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  610. }
  611. /// <summary>
  612. /// Updates the application.
  613. /// </summary>
  614. /// <param name="package">The package that contains the update</param>
  615. /// <param name="cancellationToken">The cancellation token.</param>
  616. /// <param name="progress">The progress.</param>
  617. /// <returns>Task.</returns>
  618. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  619. {
  620. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  621. _hasUpdateAvailable = false;
  622. OnApplicationUpdated(package.version);
  623. }
  624. /// <summary>
  625. /// Configures the automatic run at startup.
  626. /// </summary>
  627. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  628. protected override void ConfigureAutoRunAtStartup(bool autorun)
  629. {
  630. if (SupportsAutoRunAtStartup)
  631. {
  632. Autorun.Configure(autorun);
  633. }
  634. }
  635. }
  636. }