MainStartup.cs 27 KB

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