MainStartup.cs 31 KB

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