ApplicationHost.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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.IO;
  8. using MediaBrowser.Common.Implementations.ScheduledTasks;
  9. using MediaBrowser.Common.MediaInfo;
  10. using MediaBrowser.Common.Net;
  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.IO;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.Localization;
  19. using MediaBrowser.Controller.MediaInfo;
  20. using MediaBrowser.Controller.Notifications;
  21. using MediaBrowser.Controller.Persistence;
  22. using MediaBrowser.Controller.Plugins;
  23. using MediaBrowser.Controller.Providers;
  24. using MediaBrowser.Controller.Resolvers;
  25. using MediaBrowser.Controller.Session;
  26. using MediaBrowser.Controller.Sorting;
  27. using MediaBrowser.IsoMounter;
  28. using MediaBrowser.Model.IO;
  29. using MediaBrowser.Model.MediaInfo;
  30. using MediaBrowser.Model.System;
  31. using MediaBrowser.Model.Updates;
  32. using MediaBrowser.Providers;
  33. using MediaBrowser.Server.Implementations;
  34. using MediaBrowser.Server.Implementations.BdInfo;
  35. using MediaBrowser.Server.Implementations.Configuration;
  36. using MediaBrowser.Server.Implementations.Drawing;
  37. using MediaBrowser.Server.Implementations.Dto;
  38. using MediaBrowser.Server.Implementations.HttpServer;
  39. using MediaBrowser.Server.Implementations.IO;
  40. using MediaBrowser.Server.Implementations.Library;
  41. using MediaBrowser.Server.Implementations.Localization;
  42. using MediaBrowser.Server.Implementations.MediaEncoder;
  43. using MediaBrowser.Server.Implementations.Persistence;
  44. using MediaBrowser.Server.Implementations.Providers;
  45. using MediaBrowser.Server.Implementations.ServerManager;
  46. using MediaBrowser.Server.Implementations.Session;
  47. using MediaBrowser.Server.Implementations.WebSocket;
  48. using MediaBrowser.ServerApplication.Implementations;
  49. using MediaBrowser.WebDashboard.Api;
  50. using System;
  51. using System.Collections.Generic;
  52. using System.Data.SQLite;
  53. using System.Diagnostics;
  54. using System.IO;
  55. using System.Linq;
  56. using System.Net;
  57. using System.Net.Cache;
  58. using System.Net.Http;
  59. using System.Reflection;
  60. using System.Threading;
  61. using System.Threading.Tasks;
  62. namespace MediaBrowser.ServerApplication
  63. {
  64. /// <summary>
  65. /// Class CompositionRoot
  66. /// </summary>
  67. public class ApplicationHost : BaseApplicationHost<ServerApplicationPaths>, IServerApplicationHost
  68. {
  69. internal const int UdpServerPort = 7359;
  70. /// <summary>
  71. /// Gets the server kernel.
  72. /// </summary>
  73. /// <value>The server kernel.</value>
  74. protected Kernel ServerKernel { get; set; }
  75. /// <summary>
  76. /// Gets the server configuration manager.
  77. /// </summary>
  78. /// <value>The server configuration manager.</value>
  79. public IServerConfigurationManager ServerConfigurationManager
  80. {
  81. get { return (IServerConfigurationManager)ConfigurationManager; }
  82. }
  83. /// <summary>
  84. /// Gets the name of the log file prefix.
  85. /// </summary>
  86. /// <value>The name of the log file prefix.</value>
  87. protected override string LogFilePrefixName
  88. {
  89. get { return "server"; }
  90. }
  91. /// <summary>
  92. /// Gets the name of the web application that can be used for url building.
  93. /// All api urls will be of the form {protocol}://{host}:{port}/{appname}/...
  94. /// </summary>
  95. /// <value>The name of the web application.</value>
  96. public string WebApplicationName
  97. {
  98. get { return "mediabrowser"; }
  99. }
  100. /// <summary>
  101. /// Gets the HTTP server URL prefix.
  102. /// </summary>
  103. /// <value>The HTTP server URL prefix.</value>
  104. public string HttpServerUrlPrefix
  105. {
  106. get
  107. {
  108. return "http://+:" + ServerConfigurationManager.Configuration.HttpServerPortNumber + "/" + WebApplicationName + "/";
  109. }
  110. }
  111. /// <summary>
  112. /// Gets the configuration manager.
  113. /// </summary>
  114. /// <returns>IConfigurationManager.</returns>
  115. protected override IConfigurationManager GetConfigurationManager()
  116. {
  117. return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer);
  118. }
  119. /// <summary>
  120. /// Gets or sets the server manager.
  121. /// </summary>
  122. /// <value>The server manager.</value>
  123. private IServerManager ServerManager { get; set; }
  124. /// <summary>
  125. /// Gets or sets the user manager.
  126. /// </summary>
  127. /// <value>The user manager.</value>
  128. public IUserManager UserManager { get; set; }
  129. /// <summary>
  130. /// Gets or sets the library manager.
  131. /// </summary>
  132. /// <value>The library manager.</value>
  133. internal ILibraryManager LibraryManager { get; set; }
  134. /// <summary>
  135. /// Gets or sets the directory watchers.
  136. /// </summary>
  137. /// <value>The directory watchers.</value>
  138. private IDirectoryWatchers DirectoryWatchers { get; set; }
  139. /// <summary>
  140. /// Gets or sets the provider manager.
  141. /// </summary>
  142. /// <value>The provider manager.</value>
  143. private IProviderManager ProviderManager { get; set; }
  144. /// <summary>
  145. /// Gets or sets the zip client.
  146. /// </summary>
  147. /// <value>The zip client.</value>
  148. private IZipClient ZipClient { get; set; }
  149. /// <summary>
  150. /// Gets or sets the HTTP server.
  151. /// </summary>
  152. /// <value>The HTTP server.</value>
  153. private IHttpServer HttpServer { get; set; }
  154. private IDtoService DtoService { get; set; }
  155. private IImageProcessor ImageProcessor { get; set; }
  156. /// <summary>
  157. /// Gets or sets the media encoder.
  158. /// </summary>
  159. /// <value>The media encoder.</value>
  160. private IMediaEncoder MediaEncoder { get; set; }
  161. private IIsoManager IsoManager { get; set; }
  162. private ILocalizationManager LocalizationManager { get; set; }
  163. /// <summary>
  164. /// Gets or sets the user data repository.
  165. /// </summary>
  166. /// <value>The user data repository.</value>
  167. private IUserDataRepository UserDataRepository { get; set; }
  168. private IUserRepository UserRepository { get; set; }
  169. internal IDisplayPreferencesRepository DisplayPreferencesRepository { get; set; }
  170. private IItemRepository ItemRepository { get; set; }
  171. private INotificationsRepository NotificationsRepository { get; set; }
  172. public bool IsBackgroundService
  173. {
  174. get { return _appInterface != null && _appInterface.IsBackgroundService; }
  175. }
  176. private readonly IApplicationInterface _appInterface;
  177. /// <summary>
  178. /// The full path to our startmenu shortcut
  179. /// </summary>
  180. protected override string ProductShortcutPath
  181. {
  182. get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), "Media Browser 3", "Media Browser Server.lnk"); }
  183. }
  184. private Task<IHttpServer> _httpServerCreationTask;
  185. public ApplicationHost(IApplicationInterface appInterface)
  186. {
  187. _appInterface = appInterface;
  188. }
  189. /// <summary>
  190. /// Runs the startup tasks.
  191. /// </summary>
  192. /// <returns>Task.</returns>
  193. public override async Task RunStartupTasks()
  194. {
  195. await base.RunStartupTasks().ConfigureAwait(false);
  196. DirectoryWatchers.Start();
  197. Logger.Info("Core startup complete");
  198. Parallel.ForEach(GetExports<IServerEntryPoint>(), entryPoint =>
  199. {
  200. try
  201. {
  202. entryPoint.Run();
  203. }
  204. catch (Exception ex)
  205. {
  206. Logger.ErrorException("Error in {0}", ex, entryPoint.GetType().Name);
  207. }
  208. });
  209. }
  210. /// <summary>
  211. /// Called when [logger loaded].
  212. /// </summary>
  213. protected override void OnLoggerLoaded()
  214. {
  215. base.OnLoggerLoaded();
  216. _httpServerCreationTask = Task.Run(() => ServerFactory.CreateServer(this, LogManager, "Media Browser", "dashboard/index.html"));
  217. }
  218. /// <summary>
  219. /// Registers resources that classes will depend on
  220. /// </summary>
  221. /// <returns>Task.</returns>
  222. protected override async Task RegisterResources()
  223. {
  224. ServerKernel = new Kernel();
  225. await base.RegisterResources().ConfigureAwait(false);
  226. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager));
  227. RegisterSingleInstance<IServerApplicationHost>(this);
  228. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  229. RegisterSingleInstance(ServerKernel);
  230. RegisterSingleInstance(ServerConfigurationManager);
  231. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  232. IsoManager = new IsoManager();
  233. RegisterSingleInstance(IsoManager);
  234. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  235. ZipClient = new DotNetZipClient();
  236. RegisterSingleInstance(ZipClient);
  237. UserDataRepository = new SqliteUserDataRepository(ApplicationPaths, JsonSerializer, LogManager);
  238. RegisterSingleInstance(UserDataRepository);
  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. UserManager = new UserManager(Logger, ServerConfigurationManager, UserRepository);
  246. RegisterSingleInstance(UserManager);
  247. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataRepository, () => DirectoryWatchers);
  248. RegisterSingleInstance(LibraryManager);
  249. DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager);
  250. RegisterSingleInstance(DirectoryWatchers);
  251. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager, LibraryManager);
  252. RegisterSingleInstance(ProviderManager);
  253. RegisterSingleInstance<ILibrarySearchEngine>(() => new LuceneSearchEngine(ApplicationPaths, LogManager, LibraryManager));
  254. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ZipClient, ApplicationPaths, JsonSerializer, HttpClient);
  255. RegisterSingleInstance(MediaEncoder);
  256. var clientConnectionManager = new SessionManager(UserDataRepository, ServerConfigurationManager, Logger, UserRepository);
  257. RegisterSingleInstance<ISessionManager>(clientConnectionManager);
  258. HttpServer = await _httpServerCreationTask.ConfigureAwait(false);
  259. RegisterSingleInstance(HttpServer, false);
  260. ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager);
  261. RegisterSingleInstance(ServerManager);
  262. LocalizationManager = new LocalizationManager(ServerConfigurationManager);
  263. RegisterSingleInstance(LocalizationManager);
  264. ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths);
  265. RegisterSingleInstance(ImageProcessor);
  266. DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataRepository, ItemRepository, ImageProcessor);
  267. RegisterSingleInstance(DtoService);
  268. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  269. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  270. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  271. await ConfigureNotificationsRepository().ConfigureAwait(false);
  272. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);
  273. SetKernelProperties();
  274. }
  275. /// <summary>
  276. /// Sets the kernel properties.
  277. /// </summary>
  278. private void SetKernelProperties()
  279. {
  280. Parallel.Invoke(
  281. () => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, Logger, ItemRepository),
  282. () => LocalizedStrings.StringFiles = GetExports<LocalizedStringData>(),
  283. SetStaticProperties
  284. );
  285. }
  286. private async Task<IUserRepository> GetUserRepository()
  287. {
  288. var dbFile = Path.Combine(ApplicationPaths.DataPath, "users.db");
  289. var connection = await ConnectToDb(dbFile).ConfigureAwait(false);
  290. var repo = new SqliteUserRepository(connection, JsonSerializer, LogManager);
  291. repo.Initialize();
  292. return repo;
  293. }
  294. /// <summary>
  295. /// Configures the repositories.
  296. /// </summary>
  297. /// <returns>Task.</returns>
  298. private async Task ConfigureNotificationsRepository()
  299. {
  300. var dbFile = Path.Combine(ApplicationPaths.DataPath, "notifications.db");
  301. var connection = await ConnectToDb(dbFile).ConfigureAwait(false);
  302. var repo = new SqliteNotificationsRepository(connection, LogManager);
  303. repo.Initialize();
  304. NotificationsRepository = repo;
  305. RegisterSingleInstance(NotificationsRepository);
  306. }
  307. /// <summary>
  308. /// Configures the repositories.
  309. /// </summary>
  310. /// <returns>Task.</returns>
  311. private async Task ConfigureDisplayPreferencesRepositories()
  312. {
  313. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  314. }
  315. /// <summary>
  316. /// Configures the item repositories.
  317. /// </summary>
  318. /// <returns>Task.</returns>
  319. private async Task ConfigureItemRepositories()
  320. {
  321. await ItemRepository.Initialize().ConfigureAwait(false);
  322. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  323. }
  324. /// <summary>
  325. /// Configures the user data repositories.
  326. /// </summary>
  327. /// <returns>Task.</returns>
  328. private Task ConfigureUserDataRepositories()
  329. {
  330. return UserDataRepository.Initialize();
  331. }
  332. /// <summary>
  333. /// Connects to db.
  334. /// </summary>
  335. /// <param name="dbPath">The db path.</param>
  336. /// <returns>Task{IDbConnection}.</returns>
  337. /// <exception cref="System.ArgumentNullException">dbPath</exception>
  338. private static async Task<SQLiteConnection> ConnectToDb(string dbPath)
  339. {
  340. if (string.IsNullOrEmpty(dbPath))
  341. {
  342. throw new ArgumentNullException("dbPath");
  343. }
  344. var connectionstr = new SQLiteConnectionStringBuilder
  345. {
  346. PageSize = 4096,
  347. CacheSize = 4096,
  348. SyncMode = SynchronizationModes.Normal,
  349. DataSource = dbPath,
  350. JournalMode = SQLiteJournalModeEnum.Wal
  351. };
  352. var connection = new SQLiteConnection(connectionstr.ConnectionString);
  353. await connection.OpenAsync().ConfigureAwait(false);
  354. return connection;
  355. }
  356. /// <summary>
  357. /// Dirty hacks
  358. /// </summary>
  359. private void SetStaticProperties()
  360. {
  361. // For now there's no real way to inject these properly
  362. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  363. BaseItem.ConfigurationManager = ServerConfigurationManager;
  364. BaseItem.LibraryManager = LibraryManager;
  365. BaseItem.ProviderManager = ProviderManager;
  366. BaseItem.LocalizationManager = LocalizationManager;
  367. BaseItem.ItemRepository = ItemRepository;
  368. User.XmlSerializer = XmlSerializer;
  369. User.UserManager = UserManager;
  370. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  371. }
  372. /// <summary>
  373. /// Finds the parts.
  374. /// </summary>
  375. protected override void FindParts()
  376. {
  377. if (IsFirstRun)
  378. {
  379. RegisterServerWithAdministratorAccess();
  380. }
  381. base.FindParts();
  382. HttpServer.Init(GetExports<IRestfulService>(false));
  383. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  384. StartServer(true);
  385. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  386. GetExports<IVirtualFolderCreator>(),
  387. GetExports<IItemResolver>(),
  388. GetExports<IIntroProvider>(),
  389. GetExports<IBaseItemComparer>(),
  390. GetExports<ILibraryPrescanTask>(),
  391. GetExports<ILibraryPostScanTask>(),
  392. GetExports<IMetadataSaver>());
  393. ProviderManager.AddParts(GetExports<BaseMetadataProvider>());
  394. IsoManager.AddParts(GetExports<IIsoMounter>());
  395. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  396. }
  397. /// <summary>
  398. /// Starts the server.
  399. /// </summary>
  400. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  401. private void StartServer(bool retryOnFailure)
  402. {
  403. try
  404. {
  405. ServerManager.Start(HttpServerUrlPrefix, ServerConfigurationManager.Configuration.EnableHttpLevelLogging);
  406. }
  407. catch
  408. {
  409. if (retryOnFailure)
  410. {
  411. RegisterServerWithAdministratorAccess();
  412. StartServer(false);
  413. }
  414. else
  415. {
  416. throw;
  417. }
  418. }
  419. ServerManager.StartWebSocketServer();
  420. }
  421. /// <summary>
  422. /// Called when [configuration updated].
  423. /// </summary>
  424. /// <param name="sender">The sender.</param>
  425. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  426. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  427. {
  428. base.OnConfigurationUpdated(sender, e);
  429. HttpServer.EnableHttpRequestLogging = ServerConfigurationManager.Configuration.EnableHttpLevelLogging;
  430. if (!string.Equals(HttpServer.UrlPrefix, HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  431. {
  432. NotifyPendingRestart();
  433. }
  434. else if (!ServerManager.SupportsNativeWebSocket && ServerManager.WebSocketPortNumber != ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  435. {
  436. NotifyPendingRestart();
  437. }
  438. }
  439. /// <summary>
  440. /// Restarts this instance.
  441. /// </summary>
  442. public override async Task Restart()
  443. {
  444. try
  445. {
  446. await ServerManager.SendWebSocketMessageAsync("ServerRestarting", () => string.Empty, CancellationToken.None).ConfigureAwait(false);
  447. }
  448. catch (Exception ex)
  449. {
  450. Logger.ErrorException("Error sending server restart web socket message", ex);
  451. }
  452. _appInterface.RestartApplication();
  453. }
  454. /// <summary>
  455. /// Gets or sets a value indicating whether this instance can self update.
  456. /// </summary>
  457. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  458. public override bool CanSelfUpdate
  459. {
  460. get
  461. {
  462. #if DEBUG
  463. return false;
  464. #endif
  465. return ConfigurationManager.CommonConfiguration.EnableAutoUpdate;
  466. }
  467. }
  468. /// <summary>
  469. /// Gets the composable part assemblies.
  470. /// </summary>
  471. /// <returns>IEnumerable{Assembly}.</returns>
  472. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  473. {
  474. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  475. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  476. foreach (var pluginAssembly in Directory
  477. .EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  478. .Select(LoadAssembly).Where(a => a != null))
  479. {
  480. yield return pluginAssembly;
  481. }
  482. // Include composable parts in the Api assembly
  483. yield return typeof(ApiEntryPoint).Assembly;
  484. // Include composable parts in the Dashboard assembly
  485. yield return typeof(DashboardInfo).Assembly;
  486. // Include composable parts in the Model assembly
  487. yield return typeof(SystemInfo).Assembly;
  488. // Include composable parts in the Common assembly
  489. yield return typeof(IApplicationHost).Assembly;
  490. // Include composable parts in the Controller assembly
  491. yield return typeof(Kernel).Assembly;
  492. // Include composable parts in the Providers assembly
  493. yield return typeof(ImagesByNameProvider).Assembly;
  494. // Common implementations
  495. yield return typeof(TaskManager).Assembly;
  496. // Server implementations
  497. yield return typeof(ServerApplicationPaths).Assembly;
  498. // Pismo
  499. yield return typeof(PismoIsoManager).Assembly;
  500. // Include composable parts in the running assembly
  501. yield return GetType().Assembly;
  502. }
  503. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  504. /// <summary>
  505. /// Gets the system status.
  506. /// </summary>
  507. /// <returns>SystemInfo.</returns>
  508. public virtual SystemInfo GetSystemInfo()
  509. {
  510. return new SystemInfo
  511. {
  512. HasPendingRestart = HasPendingRestart,
  513. Version = ApplicationVersion.ToString(),
  514. IsNetworkDeployed = CanSelfUpdate,
  515. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  516. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  517. FailedPluginAssemblies = FailedAssemblies.ToList(),
  518. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  519. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  520. Id = _systemId,
  521. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  522. MacAddress = GetMacAddress(),
  523. HttpServerPortNumber = ServerConfigurationManager.Configuration.HttpServerPortNumber,
  524. IsBackgroundService = IsBackgroundService
  525. };
  526. }
  527. /// <summary>
  528. /// Gets the mac address.
  529. /// </summary>
  530. /// <returns>System.String.</returns>
  531. private string GetMacAddress()
  532. {
  533. try
  534. {
  535. return NetworkManager.GetMacAddress();
  536. }
  537. catch (Exception ex)
  538. {
  539. Logger.ErrorException("Error getting mac address", ex);
  540. return null;
  541. }
  542. }
  543. /// <summary>
  544. /// Shuts down.
  545. /// </summary>
  546. public override async Task Shutdown()
  547. {
  548. try
  549. {
  550. await ServerManager.SendWebSocketMessageAsync("ServerShuttingDown", () => string.Empty, CancellationToken.None).ConfigureAwait(false);
  551. }
  552. catch (Exception ex)
  553. {
  554. Logger.ErrorException("Error sending server shutdown web socket message", ex);
  555. }
  556. _appInterface.ShutdownApplication();
  557. }
  558. /// <summary>
  559. /// Registers the server with administrator access.
  560. /// </summary>
  561. private void RegisterServerWithAdministratorAccess()
  562. {
  563. Logger.Info("Requesting administrative access to authorize http server");
  564. // Create a temp file path to extract the bat file to
  565. var tmpFile = Path.Combine(ConfigurationManager.CommonApplicationPaths.TempDirectory, Guid.NewGuid() + ".bat");
  566. // Extract the bat file
  567. using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.ServerApplication.RegisterServer.bat"))
  568. {
  569. using (var fileStream = File.Create(tmpFile))
  570. {
  571. stream.CopyTo(fileStream);
  572. }
  573. }
  574. var startInfo = new ProcessStartInfo
  575. {
  576. FileName = tmpFile,
  577. Arguments = string.Format("{0} {1} {2} {3}", ServerConfigurationManager.Configuration.HttpServerPortNumber,
  578. HttpServerUrlPrefix,
  579. UdpServerPort,
  580. ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber),
  581. CreateNoWindow = true,
  582. WindowStyle = ProcessWindowStyle.Hidden,
  583. Verb = "runas",
  584. ErrorDialog = false
  585. };
  586. using (var process = Process.Start(startInfo))
  587. {
  588. process.WaitForExit();
  589. }
  590. }
  591. /// <summary>
  592. /// Checks for update.
  593. /// </summary>
  594. /// <param name="cancellationToken">The cancellation token.</param>
  595. /// <param name="progress">The progress.</param>
  596. /// <returns>Task{CheckForUpdateResult}.</returns>
  597. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  598. IProgress<double> progress)
  599. {
  600. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  601. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  602. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  603. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  604. }
  605. /// <summary>
  606. /// Updates the application.
  607. /// </summary>
  608. /// <param name="package">The package that contains the update</param>
  609. /// <param name="cancellationToken">The cancellation token.</param>
  610. /// <param name="progress">The progress.</param>
  611. /// <returns>Task.</returns>
  612. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  613. {
  614. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  615. OnApplicationUpdated(package.version);
  616. }
  617. /// <summary>
  618. /// Gets the HTTP message handler.
  619. /// </summary>
  620. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  621. /// <returns>HttpMessageHandler.</returns>
  622. protected override HttpMessageHandler GetHttpMessageHandler(bool enableHttpCompression)
  623. {
  624. return new WebRequestHandler
  625. {
  626. CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate),
  627. AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None
  628. };
  629. }
  630. }
  631. }