ApplicationHost.cs 31 KB

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