MainStartup.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. using MediaBrowser.Model.Logging;
  2. using MediaBrowser.Server.Startup.Common;
  3. using MediaBrowser.ServerApplication.Native;
  4. using MediaBrowser.ServerApplication.Splash;
  5. using MediaBrowser.ServerApplication.Updates;
  6. using Microsoft.Win32;
  7. using System;
  8. using System.Configuration.Install;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Management;
  13. using System.Runtime.InteropServices;
  14. using System.ServiceProcess;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using System.Windows.Forms;
  19. using Emby.Server.Core.Cryptography;
  20. using Emby.Drawing;
  21. using Emby.Server.Core;
  22. using Emby.Server.Implementations;
  23. using Emby.Server.Implementations.Browser;
  24. using Emby.Server.Implementations.EnvironmentInfo;
  25. using Emby.Server.Implementations.IO;
  26. using Emby.Server.Implementations.Logging;
  27. using MediaBrowser.Common.Net;
  28. using MediaBrowser.Model.IO;
  29. using SystemEvents = Emby.Server.Implementations.SystemEvents;
  30. namespace MediaBrowser.ServerApplication
  31. {
  32. public class MainStartup
  33. {
  34. private static ApplicationHost _appHost;
  35. private static ILogger _logger;
  36. public static bool IsRunningAsService = false;
  37. private static bool _canRestartService = false;
  38. private static bool _appHostDisposed;
  39. [DllImport("kernel32.dll", SetLastError = true)]
  40. static extern bool SetDllDirectory(string lpPathName);
  41. public static string ApplicationPath;
  42. private static IFileSystem FileSystem;
  43. /// <summary>
  44. /// Defines the entry point of the application.
  45. /// </summary>
  46. [STAThread]
  47. public static void Main()
  48. {
  49. var options = new StartupOptions(Environment.GetCommandLineArgs());
  50. IsRunningAsService = options.ContainsOption("-service");
  51. if (IsRunningAsService)
  52. {
  53. //_canRestartService = CanRestartWindowsService();
  54. }
  55. var currentProcess = Process.GetCurrentProcess();
  56. ApplicationPath = currentProcess.MainModule.FileName;
  57. var architecturePath = Path.Combine(Path.GetDirectoryName(ApplicationPath), Environment.Is64BitProcess ? "x64" : "x86");
  58. var success = SetDllDirectory(architecturePath);
  59. SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
  60. var appPaths = CreateApplicationPaths(ApplicationPath, IsRunningAsService);
  61. var logManager = new SimpleLogManager(appPaths.LogDirectoryPath, "server");
  62. logManager.ReloadLogger(LogSeverity.Debug);
  63. logManager.AddConsoleOutput();
  64. var logger = _logger = logManager.GetLogger("Main");
  65. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  66. // Install directly
  67. if (options.ContainsOption("-installservice"))
  68. {
  69. logger.Info("Performing service installation");
  70. InstallService(ApplicationPath, logger);
  71. return;
  72. }
  73. // Restart with admin rights, then install
  74. if (options.ContainsOption("-installserviceasadmin"))
  75. {
  76. logger.Info("Performing service installation");
  77. RunServiceInstallation(ApplicationPath);
  78. return;
  79. }
  80. // Uninstall directly
  81. if (options.ContainsOption("-uninstallservice"))
  82. {
  83. logger.Info("Performing service uninstallation");
  84. UninstallService(ApplicationPath, logger);
  85. return;
  86. }
  87. // Restart with admin rights, then uninstall
  88. if (options.ContainsOption("-uninstallserviceasadmin"))
  89. {
  90. logger.Info("Performing service uninstallation");
  91. RunServiceUninstallation(ApplicationPath);
  92. return;
  93. }
  94. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  95. RunServiceInstallationIfNeeded(ApplicationPath);
  96. if (IsAlreadyRunning(ApplicationPath, currentProcess))
  97. {
  98. logger.Info("Shutting down because another instance of Emby Server is already running.");
  99. return;
  100. }
  101. if (PerformUpdateIfNeeded(appPaths, logger))
  102. {
  103. logger.Info("Exiting to perform application update.");
  104. return;
  105. }
  106. try
  107. {
  108. RunApplication(appPaths, logManager, IsRunningAsService, options);
  109. }
  110. finally
  111. {
  112. OnServiceShutdown();
  113. }
  114. }
  115. /// <summary>
  116. /// Determines whether [is already running] [the specified current process].
  117. /// </summary>
  118. /// <param name="applicationPath">The application path.</param>
  119. /// <param name="currentProcess">The current process.</param>
  120. /// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
  121. private static bool IsAlreadyRunning(string applicationPath, Process currentProcess)
  122. {
  123. var duplicate = Process.GetProcesses().FirstOrDefault(i =>
  124. {
  125. try
  126. {
  127. if (currentProcess.Id == i.Id)
  128. {
  129. return false;
  130. }
  131. }
  132. catch (Exception)
  133. {
  134. return false;
  135. }
  136. try
  137. {
  138. //_logger.Info("Module: {0}", i.MainModule.FileName);
  139. if (string.Equals(applicationPath, i.MainModule.FileName, StringComparison.OrdinalIgnoreCase))
  140. {
  141. return true;
  142. }
  143. return false;
  144. }
  145. catch (Exception)
  146. {
  147. return false;
  148. }
  149. });
  150. if (duplicate != null)
  151. {
  152. _logger.Info("Found a duplicate process. Giving it time to exit.");
  153. if (!duplicate.WaitForExit(40000))
  154. {
  155. _logger.Info("The duplicate process did not exit.");
  156. return true;
  157. }
  158. }
  159. if (!IsRunningAsService)
  160. {
  161. return IsAlreadyRunningAsService(applicationPath);
  162. }
  163. return false;
  164. }
  165. private static bool IsAlreadyRunningAsService(string applicationPath)
  166. {
  167. try
  168. {
  169. var serviceName = BackgroundService.GetExistingServiceName();
  170. WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE State = 'Running' AND Name = '{0}'", serviceName));
  171. ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery);
  172. ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
  173. foreach (ManagementObject managementObject in managementObjectCollection)
  174. {
  175. var obj = managementObject.GetPropertyValue("PathName");
  176. if (obj == null)
  177. {
  178. continue;
  179. }
  180. var path = obj.ToString();
  181. _logger.Info("Service path: {0}", path);
  182. // Need to use indexOf instead of equality because the path will have the full service command line
  183. if (path.IndexOf(applicationPath, StringComparison.OrdinalIgnoreCase) != -1)
  184. {
  185. _logger.Info("The windows service is already running");
  186. MessageBox.Show("Emby Server is already running as a Windows Service. Only one instance is allowed at a time. To run as a tray icon, shut down the Windows Service.");
  187. return true;
  188. }
  189. }
  190. }
  191. catch (COMException)
  192. {
  193. // Catch errors thrown due to WMI not being initialized
  194. }
  195. return false;
  196. }
  197. /// <summary>
  198. /// Creates the application paths.
  199. /// </summary>
  200. /// <param name="applicationPath">The application path.</param>
  201. /// <param name="runAsService">if set to <c>true</c> [run as service].</param>
  202. /// <returns>ServerApplicationPaths.</returns>
  203. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, bool runAsService)
  204. {
  205. var appFolderPath = Path.GetDirectoryName(applicationPath);
  206. var resourcesPath = Path.GetDirectoryName(applicationPath);
  207. if (runAsService)
  208. {
  209. var systemPath = Path.GetDirectoryName(applicationPath);
  210. var programDataPath = Path.GetDirectoryName(systemPath);
  211. return new ServerApplicationPaths(programDataPath, appFolderPath, resourcesPath);
  212. }
  213. return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), appFolderPath, resourcesPath);
  214. }
  215. /// <summary>
  216. /// Gets a value indicating whether this instance can self restart.
  217. /// </summary>
  218. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  219. public static bool CanSelfRestart
  220. {
  221. get
  222. {
  223. if (IsRunningAsService)
  224. {
  225. return _canRestartService;
  226. }
  227. else
  228. {
  229. return true;
  230. }
  231. }
  232. }
  233. /// <summary>
  234. /// Gets a value indicating whether this instance can self update.
  235. /// </summary>
  236. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  237. public static bool CanSelfUpdate
  238. {
  239. get
  240. {
  241. #if DEBUG
  242. return false;
  243. #endif
  244. if (IsRunningAsService)
  245. {
  246. return _canRestartService;
  247. }
  248. else
  249. {
  250. return true;
  251. }
  252. }
  253. }
  254. /// <summary>
  255. /// Runs the application.
  256. /// </summary>
  257. /// <param name="appPaths">The app paths.</param>
  258. /// <param name="logManager">The log manager.</param>
  259. /// <param name="runService">if set to <c>true</c> [run service].</param>
  260. /// <param name="options">The options.</param>
  261. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
  262. {
  263. var environmentInfo = new EnvironmentInfo();
  264. var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, appPaths.TempDirectory);
  265. FileSystem = fileSystem;
  266. _appHost = new WindowsAppHost(appPaths,
  267. logManager,
  268. options,
  269. fileSystem,
  270. new PowerManagement(),
  271. "emby.windows.zip",
  272. environmentInfo,
  273. new NullImageEncoder(),
  274. new SystemEvents(logManager.GetLogger("SystemEvents")),
  275. new Networking.NetworkManager(logManager.GetLogger("NetworkManager")));
  276. var initProgress = new Progress<double>();
  277. if (!runService)
  278. {
  279. if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
  280. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  281. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  282. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  283. }
  284. var task = _appHost.Init(initProgress);
  285. Task.WaitAll(task);
  286. if (!runService)
  287. {
  288. task = InstallVcredist2013IfNeeded(_appHost, _logger);
  289. Task.WaitAll(task);
  290. // needed by skia
  291. task = InstallVcredist2015IfNeeded(_appHost, _logger);
  292. Task.WaitAll(task);
  293. }
  294. // set image encoder here
  295. _appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => _appHost.HttpClient, appPaths);
  296. task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  297. if (runService)
  298. {
  299. StartService(logManager);
  300. }
  301. else
  302. {
  303. Task.WaitAll(task);
  304. Microsoft.Win32.SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  305. HideSplashScreen();
  306. ShowTrayIcon();
  307. }
  308. }
  309. private static ServerNotifyIcon _serverNotifyIcon;
  310. private static TaskScheduler _mainTaskScheduler;
  311. private static void ShowTrayIcon()
  312. {
  313. //Application.EnableVisualStyles();
  314. //Application.SetCompatibleTextRenderingDefault(false);
  315. _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager);
  316. _mainTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
  317. Application.Run();
  318. }
  319. internal static SplashForm _splash;
  320. private static Thread _splashThread;
  321. private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
  322. {
  323. var thread = new Thread(() =>
  324. {
  325. _splash = new SplashForm(appVersion, progress);
  326. _splash.ShowDialog();
  327. });
  328. thread.SetApartmentState(ApartmentState.STA);
  329. thread.IsBackground = true;
  330. thread.Start();
  331. _splashThread = thread;
  332. }
  333. private static void HideSplashScreen()
  334. {
  335. if (_splash != null)
  336. {
  337. Action act = () =>
  338. {
  339. _splash.Close();
  340. _splashThread = null;
  341. };
  342. _splash.Invoke(act);
  343. }
  344. }
  345. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  346. {
  347. if (e.Reason == SessionSwitchReason.SessionLogon)
  348. {
  349. BrowserLauncher.OpenDashboard(_appHost);
  350. }
  351. }
  352. public static void Invoke(Action action)
  353. {
  354. if (IsRunningAsService)
  355. {
  356. action();
  357. }
  358. else
  359. {
  360. Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, _mainTaskScheduler ?? TaskScheduler.Current);
  361. }
  362. }
  363. /// <summary>
  364. /// Starts the service.
  365. /// </summary>
  366. private static void StartService(ILogManager logManager)
  367. {
  368. var service = new BackgroundService(logManager.GetLogger("Service"));
  369. service.Disposed += service_Disposed;
  370. ServiceBase.Run(service);
  371. }
  372. /// <summary>
  373. /// Handles the Disposed event of the service control.
  374. /// </summary>
  375. /// <param name="sender">The source of the event.</param>
  376. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  377. static void service_Disposed(object sender, EventArgs e)
  378. {
  379. OnServiceShutdown();
  380. }
  381. private static void OnServiceShutdown()
  382. {
  383. _logger.Info("Shutting down");
  384. DisposeAppHost();
  385. }
  386. /// <summary>
  387. /// Installs the service.
  388. /// </summary>
  389. private static void InstallService(string applicationPath, ILogger logger)
  390. {
  391. try
  392. {
  393. ManagedInstallerClass.InstallHelper(new[] { applicationPath });
  394. logger.Info("Service installation succeeded");
  395. }
  396. catch (Exception ex)
  397. {
  398. logger.ErrorException("Uninstall failed", ex);
  399. }
  400. }
  401. /// <summary>
  402. /// Uninstalls the service.
  403. /// </summary>
  404. private static void UninstallService(string applicationPath, ILogger logger)
  405. {
  406. try
  407. {
  408. ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
  409. logger.Info("Service uninstallation succeeded");
  410. }
  411. catch (Exception ex)
  412. {
  413. logger.ErrorException("Uninstall failed", ex);
  414. }
  415. }
  416. private static void RunServiceInstallationIfNeeded(string applicationPath)
  417. {
  418. var serviceName = BackgroundService.GetExistingServiceName();
  419. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName);
  420. if (ctl == null)
  421. {
  422. RunServiceInstallation(applicationPath);
  423. }
  424. }
  425. /// <summary>
  426. /// Runs the service installation.
  427. /// </summary>
  428. private static void RunServiceInstallation(string applicationPath)
  429. {
  430. var startInfo = new ProcessStartInfo
  431. {
  432. FileName = applicationPath,
  433. Arguments = "-installservice",
  434. CreateNoWindow = true,
  435. WindowStyle = ProcessWindowStyle.Hidden,
  436. Verb = "runas",
  437. ErrorDialog = false
  438. };
  439. using (var process = Process.Start(startInfo))
  440. {
  441. process.WaitForExit();
  442. }
  443. }
  444. /// <summary>
  445. /// Runs the service uninstallation.
  446. /// </summary>
  447. private static void RunServiceUninstallation(string applicationPath)
  448. {
  449. var startInfo = new ProcessStartInfo
  450. {
  451. FileName = applicationPath,
  452. Arguments = "-uninstallservice",
  453. CreateNoWindow = true,
  454. WindowStyle = ProcessWindowStyle.Hidden,
  455. Verb = "runas",
  456. ErrorDialog = false
  457. };
  458. using (var process = Process.Start(startInfo))
  459. {
  460. process.WaitForExit();
  461. }
  462. }
  463. /// <summary>
  464. /// Handles the UnhandledException event of the CurrentDomain control.
  465. /// </summary>
  466. /// <param name="sender">The source of the event.</param>
  467. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  468. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  469. {
  470. var exception = (Exception)e.ExceptionObject;
  471. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager, FileSystem, new ConsoleLogger()).Log(exception);
  472. if (!IsRunningAsService)
  473. {
  474. MessageBox.Show("Unhandled exception: " + exception.Message);
  475. }
  476. if (!Debugger.IsAttached)
  477. {
  478. Environment.Exit(Marshal.GetHRForException(exception));
  479. }
  480. }
  481. /// <summary>
  482. /// Performs the update if needed.
  483. /// </summary>
  484. /// <param name="appPaths">The app paths.</param>
  485. /// <param name="logger">The logger.</param>
  486. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  487. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  488. {
  489. // Not supported
  490. if (IsRunningAsService)
  491. {
  492. return false;
  493. }
  494. // Look for the existence of an update archive
  495. var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
  496. if (File.Exists(updateArchive))
  497. {
  498. logger.Info("An update is available from {0}", updateArchive);
  499. // Update is there - execute update
  500. try
  501. {
  502. var serviceName = IsRunningAsService ? BackgroundService.GetExistingServiceName() : string.Empty;
  503. new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
  504. // And just let the app exit so it can update
  505. return true;
  506. }
  507. catch (Exception e)
  508. {
  509. logger.ErrorException("Error starting updater.", e);
  510. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  511. }
  512. }
  513. return false;
  514. }
  515. public static void Shutdown()
  516. {
  517. if (IsRunningAsService)
  518. {
  519. ShutdownWindowsService();
  520. }
  521. else
  522. {
  523. DisposeAppHost();
  524. ShutdownWindowsApplication();
  525. }
  526. }
  527. public static void Restart()
  528. {
  529. DisposeAppHost();
  530. if (IsRunningAsService)
  531. {
  532. RestartWindowsService();
  533. }
  534. else
  535. {
  536. //_logger.Info("Hiding server notify icon");
  537. //_serverNotifyIcon.Visible = false;
  538. _logger.Info("Starting new instance");
  539. //Application.Restart();
  540. Process.Start(ApplicationPath);
  541. ShutdownWindowsApplication();
  542. }
  543. }
  544. private static void DisposeAppHost()
  545. {
  546. if (!_appHostDisposed)
  547. {
  548. _logger.Info("Disposing app host");
  549. _appHostDisposed = true;
  550. _appHost.Dispose();
  551. _logger.Info("App host dispose complete");
  552. }
  553. }
  554. private static void ShutdownWindowsApplication()
  555. {
  556. if (_serverNotifyIcon != null)
  557. {
  558. _serverNotifyIcon.Dispose();
  559. _serverNotifyIcon = null;
  560. }
  561. _logger.Info("Calling Application.Exit");
  562. //Application.Exit();
  563. Environment.Exit(0);
  564. }
  565. private static void ShutdownWindowsService()
  566. {
  567. _logger.Info("Stopping background service");
  568. var service = new ServiceController(BackgroundService.GetExistingServiceName());
  569. service.Refresh();
  570. if (service.Status == ServiceControllerStatus.Running)
  571. {
  572. service.Stop();
  573. }
  574. }
  575. private static void RestartWindowsService()
  576. {
  577. _logger.Info("Restarting background service");
  578. var startInfo = new ProcessStartInfo
  579. {
  580. FileName = "cmd.exe",
  581. CreateNoWindow = true,
  582. WindowStyle = ProcessWindowStyle.Hidden,
  583. Verb = "runas",
  584. ErrorDialog = false,
  585. Arguments = String.Format("/c sc stop {0} & sc start {0} & sc start {0}", BackgroundService.GetExistingServiceName())
  586. };
  587. Process.Start(startInfo);
  588. }
  589. private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger)
  590. {
  591. // Reference
  592. // http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
  593. try
  594. {
  595. var subkey = Environment.Is64BitProcess
  596. ? "SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x64"
  597. : "SOFTWARE\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x86";
  598. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  599. .OpenSubKey(subkey))
  600. {
  601. if (ndpKey != null && ndpKey.GetValue("Version") != null)
  602. {
  603. var installedVersion = ((string)ndpKey.GetValue("Version")).TrimStart('v');
  604. if (installedVersion.StartsWith("12", StringComparison.OrdinalIgnoreCase))
  605. {
  606. return;
  607. }
  608. }
  609. }
  610. }
  611. catch (Exception ex)
  612. {
  613. logger.ErrorException("Error getting .NET Framework version", ex);
  614. return;
  615. }
  616. try
  617. {
  618. await InstallVcredist(GetVcredist2013Url()).ConfigureAwait(false);
  619. }
  620. catch (Exception ex)
  621. {
  622. logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
  623. }
  624. }
  625. private static string GetVcredist2013Url()
  626. {
  627. if (Environment.Is64BitProcess)
  628. {
  629. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x64.exe";
  630. }
  631. // TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_arm.exe
  632. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x86.exe";
  633. }
  634. private static async Task InstallVcredist2015IfNeeded(ApplicationHost appHost, ILogger logger)
  635. {
  636. // Reference
  637. // http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
  638. try
  639. {
  640. RegistryKey key;
  641. if (Environment.Is64BitProcess)
  642. {
  643. key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  644. .OpenSubKey("SOFTWARE\\Classes\\Installer\\Dependencies\\{d992c12e-cab2-426f-bde3-fb8c53950b0d}");
  645. if (key == null)
  646. {
  647. key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  648. .OpenSubKey("SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\x64");
  649. }
  650. }
  651. else
  652. {
  653. key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  654. .OpenSubKey("SOFTWARE\\Classes\\Installer\\Dependencies\\{e2803110-78b3-4664-a479-3611a381656a}");
  655. if (key == null)
  656. {
  657. key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  658. .OpenSubKey("SOFTWARE\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\x86");
  659. }
  660. }
  661. if (key != null)
  662. {
  663. using (key)
  664. {
  665. var version = key.GetValue("Version");
  666. if (version != null)
  667. {
  668. var installedVersion = ((string)version).TrimStart('v');
  669. if (installedVersion.StartsWith("14", StringComparison.OrdinalIgnoreCase))
  670. {
  671. return;
  672. }
  673. }
  674. }
  675. }
  676. }
  677. catch (Exception ex)
  678. {
  679. logger.ErrorException("Error getting .NET Framework version", ex);
  680. return;
  681. }
  682. try
  683. {
  684. await InstallVcredist(GetVcredist2015Url()).ConfigureAwait(false);
  685. }
  686. catch (Exception ex)
  687. {
  688. logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
  689. }
  690. }
  691. private static string GetVcredist2015Url()
  692. {
  693. if (Environment.Is64BitProcess)
  694. {
  695. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vc_redist.x64.exe";
  696. }
  697. // TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vcredist_arm.exe
  698. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vc_redist.x86.exe";
  699. }
  700. private async static Task InstallVcredist(string url)
  701. {
  702. var httpClient = _appHost.HttpClient;
  703. var tmp = await httpClient.GetTempFile(new HttpRequestOptions
  704. {
  705. Url = url,
  706. Progress = new Progress<double>()
  707. }).ConfigureAwait(false);
  708. var exePath = Path.ChangeExtension(tmp, ".exe");
  709. File.Copy(tmp, exePath);
  710. var startInfo = new ProcessStartInfo
  711. {
  712. FileName = exePath,
  713. CreateNoWindow = true,
  714. WindowStyle = ProcessWindowStyle.Hidden,
  715. Verb = "runas",
  716. ErrorDialog = false
  717. };
  718. _logger.Info("Running {0}", startInfo.FileName);
  719. using (var process = Process.Start(startInfo))
  720. {
  721. process.WaitForExit();
  722. }
  723. }
  724. /// <summary>
  725. /// Sets the error mode.
  726. /// </summary>
  727. /// <param name="uMode">The u mode.</param>
  728. /// <returns>ErrorModes.</returns>
  729. [DllImport("kernel32.dll")]
  730. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  731. /// <summary>
  732. /// Enum ErrorModes
  733. /// </summary>
  734. [Flags]
  735. public enum ErrorModes : uint
  736. {
  737. /// <summary>
  738. /// The SYSTE m_ DEFAULT
  739. /// </summary>
  740. SYSTEM_DEFAULT = 0x0,
  741. /// <summary>
  742. /// The SE m_ FAILCRITICALERRORS
  743. /// </summary>
  744. SEM_FAILCRITICALERRORS = 0x0001,
  745. /// <summary>
  746. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  747. /// </summary>
  748. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  749. /// <summary>
  750. /// The SE m_ NOGPFAULTERRORBOX
  751. /// </summary>
  752. SEM_NOGPFAULTERRORBOX = 0x0002,
  753. /// <summary>
  754. /// The SE m_ NOOPENFILEERRORBOX
  755. /// </summary>
  756. SEM_NOOPENFILEERRORBOX = 0x8000
  757. }
  758. }
  759. }