MainStartup.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. using MediaBrowser.Model.Logging;
  2. using MediaBrowser.Server.Implementations;
  3. using MediaBrowser.Server.Startup.Common;
  4. using MediaBrowser.ServerApplication.Native;
  5. using MediaBrowser.ServerApplication.Splash;
  6. using MediaBrowser.ServerApplication.Updates;
  7. using Microsoft.Win32;
  8. using System;
  9. using System.Configuration.Install;
  10. using System.Diagnostics;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Management;
  14. using System.Runtime.InteropServices;
  15. using System.ServiceProcess;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using System.Windows.Forms;
  20. using Emby.Common.Implementations.EnvironmentInfo;
  21. using Emby.Common.Implementations.IO;
  22. using Emby.Common.Implementations.Logging;
  23. using Emby.Common.Implementations.Networking;
  24. using Emby.Server.Core.Cryptography;
  25. using Emby.Drawing;
  26. using Emby.Server.Core;
  27. using Emby.Server.Core.IO;
  28. using Emby.Server.Core.Logging;
  29. using Emby.Server.Implementations;
  30. using Emby.Server.Implementations.Browser;
  31. using Emby.Server.Implementations.IO;
  32. using Emby.Server.Implementations.Logging;
  33. using MediaBrowser.Common.Net;
  34. using MediaBrowser.Model.IO;
  35. namespace MediaBrowser.ServerApplication
  36. {
  37. public class MainStartup
  38. {
  39. private static ApplicationHost _appHost;
  40. private static ILogger _logger;
  41. public static bool IsRunningAsService = false;
  42. private static bool _canRestartService = false;
  43. private static bool _appHostDisposed;
  44. [DllImport("kernel32.dll", SetLastError = true)]
  45. static extern bool SetDllDirectory(string lpPathName);
  46. public static string ApplicationPath;
  47. private static IFileSystem FileSystem;
  48. /// <summary>
  49. /// Defines the entry point of the application.
  50. /// </summary>
  51. [STAThread]
  52. public static void Main()
  53. {
  54. var options = new StartupOptions(Environment.GetCommandLineArgs());
  55. IsRunningAsService = options.ContainsOption("-service");
  56. if (IsRunningAsService)
  57. {
  58. //_canRestartService = CanRestartWindowsService();
  59. }
  60. var currentProcess = Process.GetCurrentProcess();
  61. ApplicationPath = currentProcess.MainModule.FileName;
  62. var architecturePath = Path.Combine(Path.GetDirectoryName(ApplicationPath), Environment.Is64BitProcess ? "x64" : "x86");
  63. var success = SetDllDirectory(architecturePath);
  64. SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
  65. var appPaths = CreateApplicationPaths(ApplicationPath, IsRunningAsService);
  66. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  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. try
  112. {
  113. RunApplication(appPaths, logManager, IsRunningAsService, options);
  114. }
  115. finally
  116. {
  117. OnServiceShutdown();
  118. }
  119. }
  120. /// <summary>
  121. /// Determines whether [is already running] [the specified current process].
  122. /// </summary>
  123. /// <param name="applicationPath">The application path.</param>
  124. /// <param name="currentProcess">The current process.</param>
  125. /// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
  126. private static bool IsAlreadyRunning(string applicationPath, Process currentProcess)
  127. {
  128. var duplicate = Process.GetProcesses().FirstOrDefault(i =>
  129. {
  130. try
  131. {
  132. if (currentProcess.Id == i.Id)
  133. {
  134. return false;
  135. }
  136. }
  137. catch (Exception)
  138. {
  139. return false;
  140. }
  141. try
  142. {
  143. //_logger.Info("Module: {0}", i.MainModule.FileName);
  144. if (string.Equals(applicationPath, i.MainModule.FileName, StringComparison.OrdinalIgnoreCase))
  145. {
  146. return true;
  147. }
  148. return false;
  149. }
  150. catch (Exception)
  151. {
  152. return false;
  153. }
  154. });
  155. if (duplicate != null)
  156. {
  157. _logger.Info("Found a duplicate process. Giving it time to exit.");
  158. if (!duplicate.WaitForExit(40000))
  159. {
  160. _logger.Info("The duplicate process did not exit.");
  161. return true;
  162. }
  163. }
  164. if (!IsRunningAsService)
  165. {
  166. return IsAlreadyRunningAsService(applicationPath);
  167. }
  168. return false;
  169. }
  170. private static bool IsAlreadyRunningAsService(string applicationPath)
  171. {
  172. var serviceName = BackgroundService.GetExistingServiceName();
  173. WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE State = 'Running' AND Name = '{0}'", serviceName));
  174. ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery);
  175. ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
  176. foreach (ManagementObject managementObject in managementObjectCollection)
  177. {
  178. var obj = managementObject.GetPropertyValue("PathName");
  179. if (obj == null)
  180. {
  181. continue;
  182. }
  183. var path = obj.ToString();
  184. _logger.Info("Service path: {0}", path);
  185. // Need to use indexOf instead of equality because the path will have the full service command line
  186. if (path.IndexOf(applicationPath, StringComparison.OrdinalIgnoreCase) != -1)
  187. {
  188. _logger.Info("The windows service is already running");
  189. MessageBox.Show("Emby Server is already running as a Windows Service. Only one instance is allowed at a time. To run as a tray icon, shut down the Windows Service.");
  190. return true;
  191. }
  192. }
  193. 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. Action<string> createDirectoryFn = s => Directory.CreateDirectory(s);
  206. if (runAsService)
  207. {
  208. var systemPath = Path.GetDirectoryName(applicationPath);
  209. var programDataPath = Path.GetDirectoryName(systemPath);
  210. return new ServerApplicationPaths(programDataPath, appFolderPath, resourcesPath, createDirectoryFn);
  211. }
  212. return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), appFolderPath, resourcesPath, createDirectoryFn);
  213. }
  214. /// <summary>
  215. /// Gets a value indicating whether this instance can self restart.
  216. /// </summary>
  217. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  218. public static bool CanSelfRestart
  219. {
  220. get
  221. {
  222. if (IsRunningAsService)
  223. {
  224. return _canRestartService;
  225. }
  226. else
  227. {
  228. return true;
  229. }
  230. }
  231. }
  232. /// <summary>
  233. /// Gets a value indicating whether this instance can self update.
  234. /// </summary>
  235. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  236. public static bool CanSelfUpdate
  237. {
  238. get
  239. {
  240. #if DEBUG
  241. return false;
  242. #endif
  243. if (IsRunningAsService)
  244. {
  245. return _canRestartService;
  246. }
  247. else
  248. {
  249. return true;
  250. }
  251. }
  252. }
  253. /// <summary>
  254. /// Runs the application.
  255. /// </summary>
  256. /// <param name="appPaths">The app paths.</param>
  257. /// <param name="logManager">The log manager.</param>
  258. /// <param name="runService">if set to <c>true</c> [run service].</param>
  259. /// <param name="options">The options.</param>
  260. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
  261. {
  262. var environmentInfo = new EnvironmentInfo();
  263. var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, appPaths.TempDirectory);
  264. FileSystem = fileSystem;
  265. _appHost = new WindowsAppHost(appPaths,
  266. logManager,
  267. options,
  268. fileSystem,
  269. new PowerManagement(),
  270. "emby.windows.zip",
  271. environmentInfo,
  272. new NullImageEncoder(),
  273. new Server.Startup.Common.SystemEvents(logManager.GetLogger("SystemEvents")),
  274. new RecyclableMemoryStreamProvider(),
  275. new Networking.NetworkManager(logManager.GetLogger("NetworkManager")),
  276. GenerateCertificate,
  277. () => Environment.UserDomainName);
  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 void GenerateCertificate(string certPath, string certHost, string certPassword)
  312. {
  313. CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, certPassword, _logger);
  314. }
  315. private static ServerNotifyIcon _serverNotifyIcon;
  316. private static TaskScheduler _mainTaskScheduler;
  317. private static void ShowTrayIcon()
  318. {
  319. //Application.EnableVisualStyles();
  320. //Application.SetCompatibleTextRenderingDefault(false);
  321. _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager);
  322. _mainTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
  323. Application.Run();
  324. }
  325. internal static SplashForm _splash;
  326. private static Thread _splashThread;
  327. private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
  328. {
  329. var thread = new Thread(() =>
  330. {
  331. _splash = new SplashForm(appVersion, progress);
  332. _splash.ShowDialog();
  333. });
  334. thread.SetApartmentState(ApartmentState.STA);
  335. thread.IsBackground = true;
  336. thread.Start();
  337. _splashThread = thread;
  338. }
  339. private static void HideSplashScreen()
  340. {
  341. if (_splash != null)
  342. {
  343. Action act = () =>
  344. {
  345. _splash.Close();
  346. _splashThread = null;
  347. };
  348. _splash.Invoke(act);
  349. }
  350. }
  351. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  352. {
  353. if (e.Reason == SessionSwitchReason.SessionLogon)
  354. {
  355. BrowserLauncher.OpenDashboard(_appHost);
  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. OnServiceShutdown();
  386. }
  387. private static void OnServiceShutdown()
  388. {
  389. _logger.Info("Shutting down");
  390. DisposeAppHost();
  391. }
  392. /// <summary>
  393. /// Installs the service.
  394. /// </summary>
  395. private static void InstallService(string applicationPath, ILogger logger)
  396. {
  397. try
  398. {
  399. ManagedInstallerClass.InstallHelper(new[] { applicationPath });
  400. logger.Info("Service installation succeeded");
  401. }
  402. catch (Exception ex)
  403. {
  404. logger.ErrorException("Uninstall failed", ex);
  405. }
  406. }
  407. /// <summary>
  408. /// Uninstalls the service.
  409. /// </summary>
  410. private static void UninstallService(string applicationPath, ILogger logger)
  411. {
  412. try
  413. {
  414. ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
  415. logger.Info("Service uninstallation succeeded");
  416. }
  417. catch (Exception ex)
  418. {
  419. logger.ErrorException("Uninstall failed", ex);
  420. }
  421. }
  422. private static void RunServiceInstallationIfNeeded(string applicationPath)
  423. {
  424. var serviceName = BackgroundService.GetExistingServiceName();
  425. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName);
  426. if (ctl == null)
  427. {
  428. RunServiceInstallation(applicationPath);
  429. }
  430. }
  431. /// <summary>
  432. /// Runs the service installation.
  433. /// </summary>
  434. private static void RunServiceInstallation(string applicationPath)
  435. {
  436. var startInfo = new ProcessStartInfo
  437. {
  438. FileName = applicationPath,
  439. Arguments = "-installservice",
  440. CreateNoWindow = true,
  441. WindowStyle = ProcessWindowStyle.Hidden,
  442. Verb = "runas",
  443. ErrorDialog = false
  444. };
  445. using (var process = Process.Start(startInfo))
  446. {
  447. process.WaitForExit();
  448. }
  449. }
  450. /// <summary>
  451. /// Runs the service uninstallation.
  452. /// </summary>
  453. private static void RunServiceUninstallation(string applicationPath)
  454. {
  455. var startInfo = new ProcessStartInfo
  456. {
  457. FileName = applicationPath,
  458. Arguments = "-uninstallservice",
  459. CreateNoWindow = true,
  460. WindowStyle = ProcessWindowStyle.Hidden,
  461. Verb = "runas",
  462. ErrorDialog = false
  463. };
  464. using (var process = Process.Start(startInfo))
  465. {
  466. process.WaitForExit();
  467. }
  468. }
  469. /// <summary>
  470. /// Handles the UnhandledException event of the CurrentDomain control.
  471. /// </summary>
  472. /// <param name="sender">The source of the event.</param>
  473. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  474. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  475. {
  476. var exception = (Exception)e.ExceptionObject;
  477. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager, FileSystem, new ConsoleLogger()).Log(exception);
  478. if (!IsRunningAsService)
  479. {
  480. MessageBox.Show("Unhandled exception: " + exception.Message);
  481. }
  482. if (!Debugger.IsAttached)
  483. {
  484. Environment.Exit(Marshal.GetHRForException(exception));
  485. }
  486. }
  487. /// <summary>
  488. /// Performs the update if needed.
  489. /// </summary>
  490. /// <param name="appPaths">The app paths.</param>
  491. /// <param name="logger">The logger.</param>
  492. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  493. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  494. {
  495. // Not supported
  496. if (IsRunningAsService)
  497. {
  498. return false;
  499. }
  500. // Look for the existence of an update archive
  501. var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
  502. if (File.Exists(updateArchive))
  503. {
  504. logger.Info("An update is available from {0}", updateArchive);
  505. // Update is there - execute update
  506. try
  507. {
  508. var serviceName = IsRunningAsService ? BackgroundService.GetExistingServiceName() : string.Empty;
  509. new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
  510. // And just let the app exit so it can update
  511. return true;
  512. }
  513. catch (Exception e)
  514. {
  515. logger.ErrorException("Error starting updater.", e);
  516. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  517. }
  518. }
  519. return false;
  520. }
  521. public static void Shutdown()
  522. {
  523. if (IsRunningAsService)
  524. {
  525. ShutdownWindowsService();
  526. }
  527. else
  528. {
  529. DisposeAppHost();
  530. ShutdownWindowsApplication();
  531. }
  532. }
  533. public static void Restart()
  534. {
  535. DisposeAppHost();
  536. if (IsRunningAsService)
  537. {
  538. RestartWindowsService();
  539. }
  540. else
  541. {
  542. //_logger.Info("Hiding server notify icon");
  543. //_serverNotifyIcon.Visible = false;
  544. _logger.Info("Starting new instance");
  545. //Application.Restart();
  546. Process.Start(ApplicationPath);
  547. ShutdownWindowsApplication();
  548. }
  549. }
  550. private static void DisposeAppHost()
  551. {
  552. if (!_appHostDisposed)
  553. {
  554. _logger.Info("Disposing app host");
  555. _appHostDisposed = true;
  556. _appHost.Dispose();
  557. _logger.Info("App host dispose complete");
  558. }
  559. }
  560. private static void ShutdownWindowsApplication()
  561. {
  562. if (_serverNotifyIcon != null)
  563. {
  564. _serverNotifyIcon.Dispose();
  565. _serverNotifyIcon = null;
  566. }
  567. _logger.Info("Calling Application.Exit");
  568. //Application.Exit();
  569. Environment.Exit(0);
  570. }
  571. private static void ShutdownWindowsService()
  572. {
  573. _logger.Info("Stopping background service");
  574. var service = new ServiceController(BackgroundService.GetExistingServiceName());
  575. service.Refresh();
  576. if (service.Status == ServiceControllerStatus.Running)
  577. {
  578. service.Stop();
  579. }
  580. }
  581. private static void RestartWindowsService()
  582. {
  583. _logger.Info("Restarting background service");
  584. var startInfo = new ProcessStartInfo
  585. {
  586. FileName = "cmd.exe",
  587. CreateNoWindow = true,
  588. WindowStyle = ProcessWindowStyle.Hidden,
  589. Verb = "runas",
  590. ErrorDialog = false,
  591. Arguments = String.Format("/c sc stop {0} & sc start {0} & sc start {0}", BackgroundService.GetExistingServiceName())
  592. };
  593. Process.Start(startInfo);
  594. }
  595. private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger)
  596. {
  597. // Reference
  598. // http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
  599. try
  600. {
  601. var subkey = Environment.Is64BitProcess
  602. ? "SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x64"
  603. : "SOFTWARE\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x86";
  604. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  605. .OpenSubKey(subkey))
  606. {
  607. if (ndpKey != null && ndpKey.GetValue("Version") != null)
  608. {
  609. var installedVersion = ((string)ndpKey.GetValue("Version")).TrimStart('v');
  610. if (installedVersion.StartsWith("12", StringComparison.OrdinalIgnoreCase))
  611. {
  612. return;
  613. }
  614. }
  615. }
  616. }
  617. catch (Exception ex)
  618. {
  619. logger.ErrorException("Error getting .NET Framework version", ex);
  620. return;
  621. }
  622. try
  623. {
  624. await InstallVcredist(GetVcredist2013Url()).ConfigureAwait(false);
  625. }
  626. catch (Exception ex)
  627. {
  628. logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
  629. }
  630. }
  631. private static string GetVcredist2013Url()
  632. {
  633. if (Environment.Is64BitProcess)
  634. {
  635. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x64.exe";
  636. }
  637. // TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_arm.exe
  638. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x86.exe";
  639. }
  640. private static async Task InstallVcredist2015IfNeeded(ApplicationHost appHost, ILogger logger)
  641. {
  642. // Reference
  643. // http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
  644. try
  645. {
  646. var subkey = Environment.Is64BitProcess
  647. ? "SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\x64"
  648. : "SOFTWARE\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\x86";
  649. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  650. .OpenSubKey(subkey))
  651. {
  652. if (ndpKey != null && ndpKey.GetValue("Version") != null)
  653. {
  654. var installedVersion = ((string)ndpKey.GetValue("Version")).TrimStart('v');
  655. if (installedVersion.StartsWith("14", StringComparison.OrdinalIgnoreCase))
  656. {
  657. return;
  658. }
  659. }
  660. }
  661. }
  662. catch (Exception ex)
  663. {
  664. logger.ErrorException("Error getting .NET Framework version", ex);
  665. return;
  666. }
  667. try
  668. {
  669. await InstallVcredist(GetVcredist2015Url()).ConfigureAwait(false);
  670. }
  671. catch (Exception ex)
  672. {
  673. logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
  674. }
  675. }
  676. private static string GetVcredist2015Url()
  677. {
  678. if (Environment.Is64BitProcess)
  679. {
  680. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vc_redist.x64.exe";
  681. }
  682. // TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vcredist_arm.exe
  683. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vc_redist.x86.exe";
  684. }
  685. private async static Task InstallVcredist(string url)
  686. {
  687. var httpClient = _appHost.HttpClient;
  688. var tmp = await httpClient.GetTempFile(new HttpRequestOptions
  689. {
  690. Url = url,
  691. Progress = new Progress<double>()
  692. }).ConfigureAwait(false);
  693. var exePath = Path.ChangeExtension(tmp, ".exe");
  694. File.Copy(tmp, exePath);
  695. var startInfo = new ProcessStartInfo
  696. {
  697. FileName = exePath,
  698. CreateNoWindow = true,
  699. WindowStyle = ProcessWindowStyle.Hidden,
  700. Verb = "runas",
  701. ErrorDialog = false
  702. };
  703. _logger.Info("Running {0}", startInfo.FileName);
  704. using (var process = Process.Start(startInfo))
  705. {
  706. process.WaitForExit();
  707. }
  708. }
  709. /// <summary>
  710. /// Sets the error mode.
  711. /// </summary>
  712. /// <param name="uMode">The u mode.</param>
  713. /// <returns>ErrorModes.</returns>
  714. [DllImport("kernel32.dll")]
  715. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  716. /// <summary>
  717. /// Enum ErrorModes
  718. /// </summary>
  719. [Flags]
  720. public enum ErrorModes : uint
  721. {
  722. /// <summary>
  723. /// The SYSTE m_ DEFAULT
  724. /// </summary>
  725. SYSTEM_DEFAULT = 0x0,
  726. /// <summary>
  727. /// The SE m_ FAILCRITICALERRORS
  728. /// </summary>
  729. SEM_FAILCRITICALERRORS = 0x0001,
  730. /// <summary>
  731. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  732. /// </summary>
  733. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  734. /// <summary>
  735. /// The SE m_ NOGPFAULTERRORBOX
  736. /// </summary>
  737. SEM_NOGPFAULTERRORBOX = 0x0002,
  738. /// <summary>
  739. /// The SE m_ NOOPENFILEERRORBOX
  740. /// </summary>
  741. SEM_NOOPENFILEERRORBOX = 0x8000
  742. }
  743. }
  744. }