MainStartup.cs 27 KB

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