MainStartup.cs 28 KB

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