ApplicationHost.cs 31 KB

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