ApplicationHost.cs 33 KB

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