2
0

ApplicationHost.cs 31 KB

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