ApplicationHost.cs 30 KB

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