ApplicationHost.cs 30 KB

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