ApplicationHost.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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 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));
  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);
  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);
  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<ILibraryPrescanTask>(),
  416. GetExports<ILibraryPostScanTask>(),
  417. GetExports<IPeoplePrescanTask>(),
  418. GetExports<IMetadataSaver>());
  419. ProviderManager.AddParts(GetExports<BaseMetadataProvider>(), GetExports<IImageProvider>(), GetExports<IMetadataService>(), GetExports<IMetadataProvider>());
  420. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  421. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  422. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  423. }
  424. /// <summary>
  425. /// Starts the server.
  426. /// </summary>
  427. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  428. private void StartServer(bool retryOnFailure)
  429. {
  430. try
  431. {
  432. ServerManager.Start(HttpServerUrlPrefixes, ServerConfigurationManager.Configuration.EnableHttpLevelLogging);
  433. }
  434. catch (Exception ex)
  435. {
  436. Logger.ErrorException("Error starting http server", ex);
  437. if (retryOnFailure)
  438. {
  439. RegisterServerWithAdministratorAccess();
  440. StartServer(false);
  441. }
  442. else
  443. {
  444. throw;
  445. }
  446. }
  447. ServerManager.StartWebSocketServer();
  448. }
  449. /// <summary>
  450. /// Called when [configuration updated].
  451. /// </summary>
  452. /// <param name="sender">The sender.</param>
  453. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  454. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  455. {
  456. base.OnConfigurationUpdated(sender, e);
  457. HttpServer.EnableHttpRequestLogging = ServerConfigurationManager.Configuration.EnableHttpLevelLogging;
  458. if (!HttpServer.UrlPrefixes.SequenceEqual(HttpServerUrlPrefixes, StringComparer.OrdinalIgnoreCase))
  459. {
  460. NotifyPendingRestart();
  461. }
  462. else if (!ServerManager.SupportsNativeWebSocket && ServerManager.WebSocketPortNumber != ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  463. {
  464. NotifyPendingRestart();
  465. }
  466. }
  467. /// <summary>
  468. /// Restarts this instance.
  469. /// </summary>
  470. public override async Task Restart()
  471. {
  472. if (!CanSelfRestart)
  473. {
  474. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  475. }
  476. try
  477. {
  478. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  479. }
  480. catch (Exception ex)
  481. {
  482. Logger.ErrorException("Error sending server restart notification", ex);
  483. }
  484. NativeApp.Restart();
  485. }
  486. /// <summary>
  487. /// Gets or sets a value indicating whether this instance can self update.
  488. /// </summary>
  489. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  490. public override bool CanSelfUpdate
  491. {
  492. get
  493. {
  494. #if DEBUG
  495. return false;
  496. #endif
  497. return NativeApp.CanSelfUpdate;
  498. }
  499. }
  500. /// <summary>
  501. /// Gets the composable part assemblies.
  502. /// </summary>
  503. /// <returns>IEnumerable{Assembly}.</returns>
  504. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  505. {
  506. var list = GetPluginAssemblies()
  507. .ToList();
  508. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  509. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  510. // Include composable parts in the Api assembly
  511. list.Add(typeof(ApiEntryPoint).Assembly);
  512. // Include composable parts in the Dashboard assembly
  513. list.Add(typeof(DashboardInfo).Assembly);
  514. // Include composable parts in the Model assembly
  515. list.Add(typeof(SystemInfo).Assembly);
  516. // Include composable parts in the Common assembly
  517. list.Add(typeof(IApplicationHost).Assembly);
  518. // Include composable parts in the Controller assembly
  519. list.Add(typeof(IServerApplicationHost).Assembly);
  520. // Include composable parts in the Providers assembly
  521. list.Add(typeof(ImagesByNameProvider).Assembly);
  522. // Common implementations
  523. list.Add(typeof(TaskManager).Assembly);
  524. // Server implementations
  525. list.Add(typeof(ServerApplicationPaths).Assembly);
  526. list.AddRange(Assemblies.GetAssembliesWithParts());
  527. // Include composable parts in the running assembly
  528. list.Add(GetType().Assembly);
  529. return list;
  530. }
  531. /// <summary>
  532. /// Gets the plugin assemblies.
  533. /// </summary>
  534. /// <returns>IEnumerable{Assembly}.</returns>
  535. private IEnumerable<Assembly> GetPluginAssemblies()
  536. {
  537. try
  538. {
  539. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  540. .Select(LoadAssembly)
  541. .Where(a => a != null)
  542. .ToList();
  543. }
  544. catch (DirectoryNotFoundException)
  545. {
  546. return new List<Assembly>();
  547. }
  548. }
  549. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  550. /// <summary>
  551. /// Gets the system status.
  552. /// </summary>
  553. /// <returns>SystemInfo.</returns>
  554. public virtual SystemInfo GetSystemInfo()
  555. {
  556. return new SystemInfo
  557. {
  558. HasPendingRestart = HasPendingRestart,
  559. Version = ApplicationVersion.ToString(),
  560. IsNetworkDeployed = CanSelfUpdate,
  561. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  562. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  563. FailedPluginAssemblies = FailedAssemblies.ToList(),
  564. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  565. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  566. Id = _systemId,
  567. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  568. LogPath = ApplicationPaths.LogDirectoryPath,
  569. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  570. CachePath = ApplicationPaths.CachePath,
  571. MacAddress = GetMacAddress(),
  572. HttpServerPortNumber = ServerConfigurationManager.Configuration.HttpServerPortNumber,
  573. OperatingSystem = Environment.OSVersion.ToString(),
  574. CanSelfRestart = CanSelfRestart,
  575. CanSelfUpdate = CanSelfUpdate,
  576. WanAddress = GetWanAddress(),
  577. HasUpdateAvailable = _hasUpdateAvailable,
  578. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  579. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  580. IsRunningAsService = IsRunningAsService
  581. };
  582. }
  583. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  584. private string GetWanAddress()
  585. {
  586. var ip = WanAddressEntryPoint.WanAddress;
  587. if (!string.IsNullOrEmpty(ip))
  588. {
  589. return "http://" + ip + ":" + ServerConfigurationManager.Configuration.HttpServerPortNumber.ToString(_usCulture);
  590. }
  591. return null;
  592. }
  593. /// <summary>
  594. /// Gets the mac address.
  595. /// </summary>
  596. /// <returns>System.String.</returns>
  597. private string GetMacAddress()
  598. {
  599. try
  600. {
  601. return NetworkManager.GetMacAddress();
  602. }
  603. catch (Exception ex)
  604. {
  605. Logger.ErrorException("Error getting mac address", ex);
  606. return null;
  607. }
  608. }
  609. /// <summary>
  610. /// Shuts down.
  611. /// </summary>
  612. public override async Task Shutdown()
  613. {
  614. try
  615. {
  616. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  617. }
  618. catch (Exception ex)
  619. {
  620. Logger.ErrorException("Error sending server shutdown notification", ex);
  621. }
  622. NativeApp.Shutdown();
  623. }
  624. /// <summary>
  625. /// Registers the server with administrator access.
  626. /// </summary>
  627. private void RegisterServerWithAdministratorAccess()
  628. {
  629. Logger.Info("Requesting administrative access to authorize http server");
  630. try
  631. {
  632. ServerAuthorization.AuthorizeServer(
  633. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  634. HttpServerUrlPrefixes.First(),
  635. ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber,
  636. UdpServerEntryPoint.PortNumber,
  637. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  638. }
  639. catch (Exception ex)
  640. {
  641. Logger.ErrorException("Error authorizing server", ex);
  642. }
  643. }
  644. private bool _hasUpdateAvailable;
  645. /// <summary>
  646. /// Checks for update.
  647. /// </summary>
  648. /// <param name="cancellationToken">The cancellation token.</param>
  649. /// <param name="progress">The progress.</param>
  650. /// <returns>Task{CheckForUpdateResult}.</returns>
  651. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  652. {
  653. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  654. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, null, ApplicationVersion,
  655. ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  656. _hasUpdateAvailable = version != null;
  657. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  658. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  659. }
  660. /// <summary>
  661. /// Updates the application.
  662. /// </summary>
  663. /// <param name="package">The package that contains the update</param>
  664. /// <param name="cancellationToken">The cancellation token.</param>
  665. /// <param name="progress">The progress.</param>
  666. /// <returns>Task.</returns>
  667. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  668. {
  669. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  670. _hasUpdateAvailable = false;
  671. OnApplicationUpdated(package.version);
  672. }
  673. /// <summary>
  674. /// Configures the automatic run at startup.
  675. /// </summary>
  676. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  677. protected override void ConfigureAutoRunAtStartup(bool autorun)
  678. {
  679. if (SupportsAutoRunAtStartup)
  680. {
  681. Autorun.Configure(autorun);
  682. }
  683. }
  684. }
  685. }