MainStartup.cs 30 KB

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