MainStartup.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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. /// <summary>
  258. /// Runs the application.
  259. /// </summary>
  260. /// <param name="appPaths">The app paths.</param>
  261. /// <param name="logManager">The log manager.</param>
  262. /// <param name="runService">if set to <c>true</c> [run service].</param>
  263. /// <param name="options">The options.</param>
  264. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
  265. {
  266. var environmentInfo = new EnvironmentInfo();
  267. var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, appPaths.TempDirectory);
  268. FileSystem = fileSystem;
  269. using (var appHost = new WindowsAppHost(appPaths,
  270. logManager,
  271. options,
  272. fileSystem,
  273. new PowerManagement(),
  274. "emby.windows.zip",
  275. environmentInfo,
  276. new NullImageEncoder(),
  277. new SystemEvents(logManager.GetLogger("SystemEvents")),
  278. new Networking.NetworkManager(logManager.GetLogger("NetworkManager"))))
  279. {
  280. var initProgress = new Progress<double>();
  281. if (!runService)
  282. {
  283. if (!options.ContainsOption("-nosplash")) ShowSplashScreen(appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
  284. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  285. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  286. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  287. }
  288. var task = appHost.Init(initProgress);
  289. Task.WaitAll(task);
  290. if (!runService)
  291. {
  292. task = InstallVcredist2013IfNeeded(appHost.HttpClient, _logger);
  293. Task.WaitAll(task);
  294. // needed by skia
  295. task = InstallVcredist2015IfNeeded(appHost.HttpClient, _logger);
  296. Task.WaitAll(task);
  297. }
  298. // set image encoder here
  299. appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => appHost.HttpClient, appPaths);
  300. task = task.ContinueWith(new Action<Task>(a => appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  301. if (runService && IsServiceInstalled())
  302. {
  303. StartService(logManager);
  304. }
  305. else
  306. {
  307. Task.WaitAll(task);
  308. HideSplashScreen();
  309. ShowTrayIcon(appHost);
  310. }
  311. }
  312. }
  313. private static ServerNotifyIcon _serverNotifyIcon;
  314. private static TaskScheduler _mainTaskScheduler;
  315. private static void ShowTrayIcon(ApplicationHost appHost)
  316. {
  317. //Application.EnableVisualStyles();
  318. //Application.SetCompatibleTextRenderingDefault(false);
  319. _serverNotifyIcon = new ServerNotifyIcon(appHost.LogManager, appHost, appHost.ServerConfigurationManager, appHost.LocalizationManager);
  320. _mainTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
  321. Application.Run();
  322. }
  323. internal static SplashForm _splash;
  324. private static Thread _splashThread;
  325. private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
  326. {
  327. var thread = new Thread(() =>
  328. {
  329. _splash = new SplashForm(appVersion, progress);
  330. _splash.ShowDialog();
  331. });
  332. thread.SetApartmentState(ApartmentState.STA);
  333. thread.IsBackground = true;
  334. thread.Start();
  335. _splashThread = thread;
  336. }
  337. private static void HideSplashScreen()
  338. {
  339. if (_splash != null)
  340. {
  341. Action act = () =>
  342. {
  343. _splash.Close();
  344. _splashThread = null;
  345. };
  346. _splash.Invoke(act);
  347. }
  348. }
  349. public static void Invoke(Action action)
  350. {
  351. if (IsRunningAsService)
  352. {
  353. action();
  354. }
  355. else
  356. {
  357. Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, _mainTaskScheduler ?? TaskScheduler.Current);
  358. }
  359. }
  360. /// <summary>
  361. /// Starts the service.
  362. /// </summary>
  363. private static void StartService(ILogManager logManager)
  364. {
  365. var service = new BackgroundService(logManager.GetLogger("Service"));
  366. ServiceBase.Run(service);
  367. }
  368. /// <summary>
  369. /// Uninstalls the service.
  370. /// </summary>
  371. private static void UninstallService(string applicationPath, ILogger logger)
  372. {
  373. try
  374. {
  375. ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
  376. logger.Info("Service uninstallation succeeded");
  377. }
  378. catch (Exception ex)
  379. {
  380. logger.ErrorException("Uninstall failed", ex);
  381. }
  382. }
  383. /// <summary>
  384. /// Runs the service uninstallation.
  385. /// </summary>
  386. private static void RunServiceUninstallation(string applicationPath)
  387. {
  388. var startInfo = new ProcessStartInfo
  389. {
  390. FileName = applicationPath,
  391. Arguments = "-uninstallservice",
  392. CreateNoWindow = true,
  393. WindowStyle = ProcessWindowStyle.Hidden,
  394. Verb = "runas",
  395. ErrorDialog = false
  396. };
  397. using (var process = Process.Start(startInfo))
  398. {
  399. process.WaitForExit();
  400. }
  401. }
  402. /// <summary>
  403. /// Handles the UnhandledException event of the CurrentDomain control.
  404. /// </summary>
  405. /// <param name="sender">The source of the event.</param>
  406. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  407. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  408. {
  409. var exception = (Exception)e.ExceptionObject;
  410. new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception);
  411. if (!IsRunningAsService)
  412. {
  413. MessageBox.Show("Unhandled exception: " + exception.Message);
  414. }
  415. if (!Debugger.IsAttached)
  416. {
  417. Environment.Exit(Marshal.GetHRForException(exception));
  418. }
  419. }
  420. /// <summary>
  421. /// Performs the update if needed.
  422. /// </summary>
  423. /// <param name="appPaths">The app paths.</param>
  424. /// <param name="logger">The logger.</param>
  425. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  426. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  427. {
  428. // Not supported
  429. if (IsRunningAsService)
  430. {
  431. return false;
  432. }
  433. // Look for the existence of an update archive
  434. var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
  435. if (File.Exists(updateArchive))
  436. {
  437. logger.Info("An update is available from {0}", updateArchive);
  438. // Update is there - execute update
  439. try
  440. {
  441. var serviceName = IsRunningAsService ? BackgroundService.GetExistingServiceName() : string.Empty;
  442. new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
  443. // And just let the app exit so it can update
  444. return true;
  445. }
  446. catch (Exception e)
  447. {
  448. logger.ErrorException("Error starting updater.", e);
  449. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  450. }
  451. }
  452. return false;
  453. }
  454. public static void Shutdown()
  455. {
  456. if (IsRunningAsService && IsServiceInstalled())
  457. {
  458. ShutdownWindowsService();
  459. }
  460. else
  461. {
  462. ShutdownWindowsApplication();
  463. }
  464. }
  465. public static void Restart()
  466. {
  467. if (IsRunningAsService)
  468. {
  469. }
  470. else
  471. {
  472. _restartOnShutdown = true;
  473. ShutdownWindowsApplication();
  474. }
  475. }
  476. private static void ShutdownWindowsApplication()
  477. {
  478. if (_serverNotifyIcon != null)
  479. {
  480. _serverNotifyIcon.Dispose();
  481. _serverNotifyIcon = null;
  482. }
  483. _logger.Info("Calling Application.Exit");
  484. Application.Exit();
  485. }
  486. private static void ShutdownWindowsService()
  487. {
  488. _logger.Info("Stopping background service");
  489. var service = new ServiceController(BackgroundService.GetExistingServiceName());
  490. service.Refresh();
  491. if (service.Status == ServiceControllerStatus.Running)
  492. {
  493. service.Stop();
  494. }
  495. }
  496. private static async Task InstallVcredist2013IfNeeded(IHttpClient httpClient, ILogger logger)
  497. {
  498. // Reference
  499. // http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
  500. try
  501. {
  502. var subkey = Environment.Is64BitProcess
  503. ? "SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x64"
  504. : "SOFTWARE\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x86";
  505. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  506. .OpenSubKey(subkey))
  507. {
  508. if (ndpKey != null && ndpKey.GetValue("Version") != null)
  509. {
  510. var installedVersion = ((string)ndpKey.GetValue("Version")).TrimStart('v');
  511. if (installedVersion.StartsWith("12", StringComparison.OrdinalIgnoreCase))
  512. {
  513. return;
  514. }
  515. }
  516. }
  517. }
  518. catch (Exception ex)
  519. {
  520. logger.ErrorException("Error getting .NET Framework version", ex);
  521. return;
  522. }
  523. try
  524. {
  525. await InstallVcredist(GetVcredist2013Url(), httpClient).ConfigureAwait(false);
  526. }
  527. catch (Exception ex)
  528. {
  529. logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
  530. }
  531. }
  532. private static string GetVcredist2013Url()
  533. {
  534. if (Environment.Is64BitProcess)
  535. {
  536. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x64.exe";
  537. }
  538. // TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_arm.exe
  539. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x86.exe";
  540. }
  541. private static async Task InstallVcredist2015IfNeeded(IHttpClient httpClient, ILogger logger)
  542. {
  543. // Reference
  544. // http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
  545. try
  546. {
  547. RegistryKey key;
  548. if (Environment.Is64BitProcess)
  549. {
  550. key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  551. .OpenSubKey("SOFTWARE\\Classes\\Installer\\Dependencies\\{d992c12e-cab2-426f-bde3-fb8c53950b0d}");
  552. if (key == null)
  553. {
  554. key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  555. .OpenSubKey("SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\x64");
  556. }
  557. }
  558. else
  559. {
  560. key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  561. .OpenSubKey("SOFTWARE\\Classes\\Installer\\Dependencies\\{e2803110-78b3-4664-a479-3611a381656a}");
  562. if (key == null)
  563. {
  564. key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  565. .OpenSubKey("SOFTWARE\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\x86");
  566. }
  567. }
  568. if (key != null)
  569. {
  570. using (key)
  571. {
  572. var version = key.GetValue("Version");
  573. if (version != null)
  574. {
  575. var installedVersion = ((string)version).TrimStart('v');
  576. if (installedVersion.StartsWith("14", StringComparison.OrdinalIgnoreCase))
  577. {
  578. return;
  579. }
  580. }
  581. }
  582. }
  583. }
  584. catch (Exception ex)
  585. {
  586. logger.ErrorException("Error getting .NET Framework version", ex);
  587. return;
  588. }
  589. try
  590. {
  591. await InstallVcredist(GetVcredist2015Url(), httpClient).ConfigureAwait(false);
  592. }
  593. catch (Exception ex)
  594. {
  595. logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
  596. }
  597. }
  598. private static string GetVcredist2015Url()
  599. {
  600. if (Environment.Is64BitProcess)
  601. {
  602. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vc_redist.x64.exe";
  603. }
  604. // TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vcredist_arm.exe
  605. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vc_redist.x86.exe";
  606. }
  607. private async static Task InstallVcredist(string url, IHttpClient httpClient)
  608. {
  609. var tmp = await httpClient.GetTempFile(new HttpRequestOptions
  610. {
  611. Url = url,
  612. Progress = new Progress<double>()
  613. }).ConfigureAwait(false);
  614. var exePath = Path.ChangeExtension(tmp, ".exe");
  615. File.Copy(tmp, exePath);
  616. var startInfo = new ProcessStartInfo
  617. {
  618. FileName = exePath,
  619. CreateNoWindow = true,
  620. WindowStyle = ProcessWindowStyle.Hidden,
  621. Verb = "runas",
  622. ErrorDialog = false
  623. };
  624. _logger.Info("Running {0}", startInfo.FileName);
  625. using (var process = Process.Start(startInfo))
  626. {
  627. process.WaitForExit();
  628. }
  629. }
  630. /// <summary>
  631. /// Sets the error mode.
  632. /// </summary>
  633. /// <param name="uMode">The u mode.</param>
  634. /// <returns>ErrorModes.</returns>
  635. [DllImport("kernel32.dll")]
  636. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  637. /// <summary>
  638. /// Enum ErrorModes
  639. /// </summary>
  640. [Flags]
  641. public enum ErrorModes : uint
  642. {
  643. /// <summary>
  644. /// The SYSTE m_ DEFAULT
  645. /// </summary>
  646. SYSTEM_DEFAULT = 0x0,
  647. /// <summary>
  648. /// The SE m_ FAILCRITICALERRORS
  649. /// </summary>
  650. SEM_FAILCRITICALERRORS = 0x0001,
  651. /// <summary>
  652. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  653. /// </summary>
  654. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  655. /// <summary>
  656. /// The SE m_ NOGPFAULTERRORBOX
  657. /// </summary>
  658. SEM_NOGPFAULTERRORBOX = 0x0002,
  659. /// <summary>
  660. /// The SE m_ NOOPENFILEERRORBOX
  661. /// </summary>
  662. SEM_NOOPENFILEERRORBOX = 0x8000
  663. }
  664. }
  665. }