ApplicationHost.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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 ZipClient();
  229. RegisterSingleInstance(ZipClient);
  230. var mediaEncoderTask = RegisterMediaEncoder();
  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. var clientConnectionManager = new SessionManager(UserDataRepository, ServerConfigurationManager, Logger, UserRepository);
  249. RegisterSingleInstance<ISessionManager>(clientConnectionManager);
  250. HttpServer = await _httpServerCreationTask.ConfigureAwait(false);
  251. RegisterSingleInstance(HttpServer, false);
  252. ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager);
  253. RegisterSingleInstance(ServerManager);
  254. LocalizationManager = new LocalizationManager(ServerConfigurationManager);
  255. RegisterSingleInstance(LocalizationManager);
  256. ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths);
  257. RegisterSingleInstance(ImageProcessor);
  258. DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataRepository, ItemRepository, ImageProcessor);
  259. RegisterSingleInstance(DtoService);
  260. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  261. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  262. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  263. await ConfigureNotificationsRepository().ConfigureAwait(false);
  264. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask, mediaEncoderTask).ConfigureAwait(false);
  265. SetKernelProperties();
  266. }
  267. /// <summary>
  268. /// Registers the media encoder.
  269. /// </summary>
  270. /// <returns>Task.</returns>
  271. private async Task RegisterMediaEncoder()
  272. {
  273. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient).GetFFMpegInfo().ConfigureAwait(false);
  274. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ApplicationPaths, JsonSerializer, info.Path, info.ProbePath, info.Version);
  275. RegisterSingleInstance(MediaEncoder);
  276. }
  277. /// <summary>
  278. /// Sets the kernel properties.
  279. /// </summary>
  280. private void SetKernelProperties()
  281. {
  282. Parallel.Invoke(
  283. () => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, Logger, ItemRepository),
  284. () => LocalizedStrings.StringFiles = GetExports<LocalizedStringData>(),
  285. SetStaticProperties
  286. );
  287. }
  288. private async Task<IUserRepository> GetUserRepository()
  289. {
  290. var dbFile = Path.Combine(ApplicationPaths.DataPath, "users.db");
  291. var connection = await ConnectToDb(dbFile).ConfigureAwait(false);
  292. var repo = new SqliteUserRepository(connection, JsonSerializer, LogManager);
  293. repo.Initialize();
  294. return repo;
  295. }
  296. /// <summary>
  297. /// Configures the repositories.
  298. /// </summary>
  299. /// <returns>Task.</returns>
  300. private async Task ConfigureNotificationsRepository()
  301. {
  302. var dbFile = Path.Combine(ApplicationPaths.DataPath, "notifications.db");
  303. var connection = await ConnectToDb(dbFile).ConfigureAwait(false);
  304. var repo = new SqliteNotificationsRepository(connection, LogManager);
  305. repo.Initialize();
  306. NotificationsRepository = repo;
  307. RegisterSingleInstance(NotificationsRepository);
  308. }
  309. /// <summary>
  310. /// Configures the repositories.
  311. /// </summary>
  312. /// <returns>Task.</returns>
  313. private async Task ConfigureDisplayPreferencesRepositories()
  314. {
  315. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  316. }
  317. /// <summary>
  318. /// Configures the item repositories.
  319. /// </summary>
  320. /// <returns>Task.</returns>
  321. private async Task ConfigureItemRepositories()
  322. {
  323. await ItemRepository.Initialize().ConfigureAwait(false);
  324. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  325. }
  326. /// <summary>
  327. /// Configures the user data repositories.
  328. /// </summary>
  329. /// <returns>Task.</returns>
  330. private Task ConfigureUserDataRepositories()
  331. {
  332. return UserDataRepository.Initialize();
  333. }
  334. /// <summary>
  335. /// Connects to db.
  336. /// </summary>
  337. /// <param name="dbPath">The db path.</param>
  338. /// <returns>Task{IDbConnection}.</returns>
  339. /// <exception cref="System.ArgumentNullException">dbPath</exception>
  340. private static async Task<SQLiteConnection> ConnectToDb(string dbPath)
  341. {
  342. if (string.IsNullOrEmpty(dbPath))
  343. {
  344. throw new ArgumentNullException("dbPath");
  345. }
  346. var connectionstr = new SQLiteConnectionStringBuilder
  347. {
  348. PageSize = 4096,
  349. CacheSize = 4096,
  350. SyncMode = SynchronizationModes.Normal,
  351. DataSource = dbPath,
  352. JournalMode = SQLiteJournalModeEnum.Wal
  353. };
  354. var connection = new SQLiteConnection(connectionstr.ConnectionString);
  355. await connection.OpenAsync().ConfigureAwait(false);
  356. return connection;
  357. }
  358. /// <summary>
  359. /// Dirty hacks
  360. /// </summary>
  361. private void SetStaticProperties()
  362. {
  363. // For now there's no real way to inject these properly
  364. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  365. BaseItem.ConfigurationManager = ServerConfigurationManager;
  366. BaseItem.LibraryManager = LibraryManager;
  367. BaseItem.ProviderManager = ProviderManager;
  368. BaseItem.LocalizationManager = LocalizationManager;
  369. BaseItem.ItemRepository = ItemRepository;
  370. User.XmlSerializer = XmlSerializer;
  371. User.UserManager = UserManager;
  372. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  373. }
  374. /// <summary>
  375. /// Finds the parts.
  376. /// </summary>
  377. protected override void FindParts()
  378. {
  379. if (IsFirstRun)
  380. {
  381. RegisterServerWithAdministratorAccess();
  382. }
  383. base.FindParts();
  384. HttpServer.Init(GetExports<IRestfulService>(false));
  385. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  386. StartServer(true);
  387. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  388. GetExports<IVirtualFolderCreator>(),
  389. GetExports<IItemResolver>(),
  390. GetExports<IIntroProvider>(),
  391. GetExports<IBaseItemComparer>(),
  392. GetExports<ILibraryPrescanTask>(),
  393. GetExports<ILibraryPostScanTask>(),
  394. GetExports<IMetadataSaver>());
  395. ProviderManager.AddParts(GetExports<BaseMetadataProvider>());
  396. IsoManager.AddParts(GetExports<IIsoMounter>());
  397. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  398. }
  399. /// <summary>
  400. /// Starts the server.
  401. /// </summary>
  402. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  403. private void StartServer(bool retryOnFailure)
  404. {
  405. try
  406. {
  407. ServerManager.Start(HttpServerUrlPrefix, ServerConfigurationManager.Configuration.EnableHttpLevelLogging);
  408. }
  409. catch
  410. {
  411. if (retryOnFailure)
  412. {
  413. RegisterServerWithAdministratorAccess();
  414. StartServer(false);
  415. }
  416. else
  417. {
  418. throw;
  419. }
  420. }
  421. ServerManager.StartWebSocketServer();
  422. }
  423. /// <summary>
  424. /// Called when [configuration updated].
  425. /// </summary>
  426. /// <param name="sender">The sender.</param>
  427. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  428. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  429. {
  430. base.OnConfigurationUpdated(sender, e);
  431. HttpServer.EnableHttpRequestLogging = ServerConfigurationManager.Configuration.EnableHttpLevelLogging;
  432. if (!string.Equals(HttpServer.UrlPrefix, HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  433. {
  434. NotifyPendingRestart();
  435. }
  436. else if (!ServerManager.SupportsNativeWebSocket && ServerManager.WebSocketPortNumber != ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  437. {
  438. NotifyPendingRestart();
  439. }
  440. }
  441. /// <summary>
  442. /// Restarts this instance.
  443. /// </summary>
  444. public override async Task Restart()
  445. {
  446. try
  447. {
  448. await ServerManager.SendWebSocketMessageAsync("ServerRestarting", () => string.Empty, CancellationToken.None).ConfigureAwait(false);
  449. }
  450. catch (Exception ex)
  451. {
  452. Logger.ErrorException("Error sending server restart web socket message", ex);
  453. }
  454. MainStartup.Restart();
  455. }
  456. /// <summary>
  457. /// Gets or sets a value indicating whether this instance can self update.
  458. /// </summary>
  459. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  460. public override bool CanSelfUpdate
  461. {
  462. get
  463. {
  464. #if DEBUG
  465. return false;
  466. #endif
  467. return ConfigurationManager.CommonConfiguration.EnableAutoUpdate;
  468. }
  469. }
  470. /// <summary>
  471. /// Gets the composable part assemblies.
  472. /// </summary>
  473. /// <returns>IEnumerable{Assembly}.</returns>
  474. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  475. {
  476. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  477. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  478. foreach (var pluginAssembly in Directory
  479. .EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  480. .Select(LoadAssembly).Where(a => a != null))
  481. {
  482. yield return pluginAssembly;
  483. }
  484. // Include composable parts in the Api assembly
  485. yield return typeof(ApiEntryPoint).Assembly;
  486. // Include composable parts in the Dashboard assembly
  487. yield return typeof(DashboardInfo).Assembly;
  488. // Include composable parts in the Model assembly
  489. yield return typeof(SystemInfo).Assembly;
  490. // Include composable parts in the Common assembly
  491. yield return typeof(IApplicationHost).Assembly;
  492. // Include composable parts in the Controller assembly
  493. yield return typeof(Kernel).Assembly;
  494. // Include composable parts in the Providers assembly
  495. yield return typeof(ImagesByNameProvider).Assembly;
  496. // Common implementations
  497. yield return typeof(TaskManager).Assembly;
  498. // Server implementations
  499. yield return typeof(ServerApplicationPaths).Assembly;
  500. // Pismo
  501. yield return typeof(PismoIsoManager).Assembly;
  502. // Include composable parts in the running assembly
  503. yield return GetType().Assembly;
  504. }
  505. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  506. /// <summary>
  507. /// Gets the system status.
  508. /// </summary>
  509. /// <returns>SystemInfo.</returns>
  510. public virtual SystemInfo GetSystemInfo()
  511. {
  512. return new SystemInfo
  513. {
  514. HasPendingRestart = HasPendingRestart,
  515. Version = ApplicationVersion.ToString(),
  516. IsNetworkDeployed = CanSelfUpdate,
  517. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  518. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  519. FailedPluginAssemblies = FailedAssemblies.ToList(),
  520. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  521. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  522. Id = _systemId,
  523. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  524. MacAddress = GetMacAddress(),
  525. HttpServerPortNumber = ServerConfigurationManager.Configuration.HttpServerPortNumber
  526. };
  527. }
  528. /// <summary>
  529. /// Gets the mac address.
  530. /// </summary>
  531. /// <returns>System.String.</returns>
  532. private string GetMacAddress()
  533. {
  534. try
  535. {
  536. return NetworkManager.GetMacAddress();
  537. }
  538. catch (Exception ex)
  539. {
  540. Logger.ErrorException("Error getting mac address", ex);
  541. return null;
  542. }
  543. }
  544. /// <summary>
  545. /// Shuts down.
  546. /// </summary>
  547. public override async Task Shutdown()
  548. {
  549. try
  550. {
  551. await ServerManager.SendWebSocketMessageAsync("ServerShuttingDown", () => string.Empty, CancellationToken.None).ConfigureAwait(false);
  552. }
  553. catch (Exception ex)
  554. {
  555. Logger.ErrorException("Error sending server shutdown web socket message", ex);
  556. }
  557. MainStartup.Shutdown();
  558. }
  559. /// <summary>
  560. /// Registers the server with administrator access.
  561. /// </summary>
  562. private void RegisterServerWithAdministratorAccess()
  563. {
  564. Logger.Info("Requesting administrative access to authorize http server");
  565. // Create a temp file path to extract the bat file to
  566. var tmpFile = Path.Combine(ConfigurationManager.CommonApplicationPaths.TempDirectory, Guid.NewGuid() + ".bat");
  567. // Extract the bat file
  568. using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.ServerApplication.RegisterServer.bat"))
  569. {
  570. using (var fileStream = File.Create(tmpFile))
  571. {
  572. stream.CopyTo(fileStream);
  573. }
  574. }
  575. var startInfo = new ProcessStartInfo
  576. {
  577. FileName = tmpFile,
  578. Arguments = string.Format("{0} {1} {2} {3}", ServerConfigurationManager.Configuration.HttpServerPortNumber,
  579. HttpServerUrlPrefix,
  580. UdpServerPort,
  581. ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber),
  582. CreateNoWindow = true,
  583. WindowStyle = ProcessWindowStyle.Hidden,
  584. Verb = "runas",
  585. ErrorDialog = false
  586. };
  587. using (var process = Process.Start(startInfo))
  588. {
  589. process.WaitForExit();
  590. }
  591. }
  592. /// <summary>
  593. /// Checks for update.
  594. /// </summary>
  595. /// <param name="cancellationToken">The cancellation token.</param>
  596. /// <param name="progress">The progress.</param>
  597. /// <returns>Task{CheckForUpdateResult}.</returns>
  598. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  599. IProgress<double> progress)
  600. {
  601. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  602. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, ApplicationVersion, ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  603. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  604. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  605. }
  606. /// <summary>
  607. /// Updates the application.
  608. /// </summary>
  609. /// <param name="package">The package that contains the update</param>
  610. /// <param name="cancellationToken">The cancellation token.</param>
  611. /// <param name="progress">The progress.</param>
  612. /// <returns>Task.</returns>
  613. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  614. {
  615. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  616. OnApplicationUpdated(package.version);
  617. }
  618. /// <summary>
  619. /// Gets the HTTP message handler.
  620. /// </summary>
  621. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  622. /// <returns>HttpMessageHandler.</returns>
  623. protected override HttpMessageHandler GetHttpMessageHandler(bool enableHttpCompression)
  624. {
  625. return new WebRequestHandler
  626. {
  627. CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate),
  628. AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None
  629. };
  630. }
  631. }
  632. }