MainStartup.cs 29 KB

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