ApplicationHost.cs 28 KB

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