ApplicationHost.cs 29 KB

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