MainStartup.cs 30 KB

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