MainStartup.cs 32 KB

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