MainStartup.cs 31 KB

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