ApplicationHost.cs 28 KB

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