MainStartup.cs 30 KB

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