MainStartup.cs 31 KB

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