MainStartup.cs 30 KB

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