MainWindow.xaml.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Net;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using System.Windows;
  10. using System.Linq;
  11. using Ionic.Zip;
  12. using MediaBrowser.Installer.Code;
  13. using Microsoft.Win32;
  14. using ServiceStack.Text;
  15. namespace MediaBrowser.Installer
  16. {
  17. /// <summary>
  18. /// Interaction logic for MainWindow.xaml
  19. /// </summary>
  20. public partial class MainWindow : Window
  21. {
  22. protected PackageVersionClass PackageClass = PackageVersionClass.Release;
  23. protected Version RequestedVersion = new Version(4,0,0,0);
  24. protected Version ActualVersion;
  25. protected string PackageName = "MBServer";
  26. protected string RootSuffix = "-Server";
  27. protected string TargetExe = "MediaBrowser.ServerApplication.exe";
  28. protected string TargetArgs = "";
  29. protected string FriendlyName = "Media Browser Server";
  30. protected string Archive = null;
  31. protected bool InstallPismo = true;
  32. protected string RootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser-Server");
  33. protected string EndInstallPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser-Server");
  34. protected bool IsUpdate = false;
  35. protected bool SystemClosing = false;
  36. protected string TempLocation = Path.Combine(Path.GetTempPath(), "MediaBrowser");
  37. protected WebClient MainClient = new WebClient();
  38. public MainWindow()
  39. {
  40. try
  41. {
  42. GetArgs();
  43. InitializeComponent();
  44. DoInstall(Archive);
  45. }
  46. catch (Exception e)
  47. {
  48. MessageBox.Show("Error: " + e.Message + " \n\n" + e.StackTrace);
  49. }
  50. }
  51. private void btnCancel_Click(object sender, RoutedEventArgs e)
  52. {
  53. this.Close();
  54. }
  55. protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
  56. {
  57. if (!SystemClosing && MessageBox.Show("Cancel Installation - Are you sure?", "Cancel", MessageBoxButton.YesNo) == MessageBoxResult.No)
  58. {
  59. e.Cancel = true;
  60. }
  61. if (MainClient.IsBusy)
  62. {
  63. MainClient.CancelAsync();
  64. while (MainClient.IsBusy)
  65. {
  66. // wait to finish
  67. }
  68. }
  69. MainClient.Dispose();
  70. ClearTempLocation(TempLocation);
  71. base.OnClosing(e);
  72. }
  73. protected void SystemClose(string message = null)
  74. {
  75. if (message != null)
  76. {
  77. MessageBox.Show(message, "Error");
  78. }
  79. SystemClosing = true;
  80. this.Close();
  81. }
  82. protected void GetArgs()
  83. {
  84. //cmd line args should be name/value pairs like: product=server archive="c:\.." caller=34552
  85. var cmdArgs = Environment.GetCommandLineArgs();
  86. var args = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  87. foreach (var pair in cmdArgs)
  88. {
  89. var nameValue = pair.Split('=');
  90. if (nameValue.Length == 2)
  91. {
  92. args[nameValue[0]] = nameValue[1];
  93. }
  94. }
  95. Archive = args.GetValueOrDefault("archive", null);
  96. if (args.GetValueOrDefault("pismo","true") == "false") InstallPismo = false;
  97. var product = args.GetValueOrDefault("product", null) ?? ConfigurationManager.AppSettings["product"] ?? "server";
  98. PackageClass = (PackageVersionClass) Enum.Parse(typeof (PackageVersionClass), args.GetValueOrDefault("class", null) ?? ConfigurationManager.AppSettings["class"] ?? "Release");
  99. RequestedVersion = new Version(args.GetValueOrDefault("version", "4.0"));
  100. var callerId = args.GetValueOrDefault("caller", null);
  101. if (callerId != null)
  102. {
  103. // Wait for our caller to exit
  104. try
  105. {
  106. var process = Process.GetProcessById(Convert.ToInt32(callerId));
  107. process.WaitForExit();
  108. }
  109. catch (ArgumentException)
  110. {
  111. // wasn't running
  112. }
  113. IsUpdate = true;
  114. }
  115. //MessageBox.Show(string.Format("Called with args: product: {0} archive: {1} caller: {2}", product, Archive, callerId));
  116. switch (product.ToLower())
  117. {
  118. case "mbt":
  119. PackageName = "MBTheater";
  120. RootSuffix = "-Theater";
  121. TargetExe = "MediaBrowser.UI.exe";
  122. FriendlyName = "Media Browser Theater";
  123. RootPath = EndInstallPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser" + RootSuffix);
  124. EndInstallPath = Path.Combine(RootPath, "system");
  125. break;
  126. case "mbc":
  127. PackageName = "MBClassic";
  128. RootSuffix = "-WMC";
  129. TargetExe = "ehshell.exe";
  130. TargetArgs = @"/nostartupanimation /entrypoint:{CE32C570-4BEC-4aeb-AD1D-CF47B91DE0B2}\{FC9ABCCC-36CB-47ac-8BAB-03E8EF5F6F22}";
  131. FriendlyName = "Media Browser Classic";
  132. RootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser" + RootSuffix);
  133. EndInstallPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "ehome");
  134. break;
  135. default:
  136. PackageName = "MBServer";
  137. RootSuffix = "-Server";
  138. TargetExe = "MediaBrowser.ServerApplication.exe";
  139. FriendlyName = "Media Browser Server";
  140. RootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser" + RootSuffix);
  141. EndInstallPath = Path.Combine(RootPath, "system");
  142. break;
  143. }
  144. }
  145. /// <summary>
  146. /// Execute the install process
  147. /// </summary>
  148. /// <returns></returns>
  149. protected async Task DoInstall(string archive)
  150. {
  151. lblStatus.Text = string.Format("Installing {0}...", FriendlyName);
  152. // Determine Package version
  153. var version = archive == null ? await GetPackageVersion() : null;
  154. ActualVersion = version != null ? version.version : new Version(3,0);
  155. // Now try and shut down the server if that is what we are installing and it is running
  156. var procs = Process.GetProcessesByName("mediabrowser.serverapplication");
  157. var server = procs.Length > 0 ? procs[0] : null;
  158. if (!IsUpdate && PackageName == "MBServer" && server != null)
  159. {
  160. lblStatus.Text = "Shutting Down Media Browser Server...";
  161. using (var client = new WebClient())
  162. {
  163. try
  164. {
  165. client.UploadString("http://localhost:8096/mediabrowser/System/Shutdown", "");
  166. try
  167. {
  168. server.WaitForExit(30000); //don't hang indefinitely
  169. }
  170. catch (ArgumentException)
  171. {
  172. // already gone
  173. }
  174. }
  175. catch (WebException e)
  176. {
  177. if (e.Status == WebExceptionStatus.Timeout || e.Message.StartsWith("Unable to connect",StringComparison.OrdinalIgnoreCase)) return; // just wasn't running
  178. MessageBox.Show("Error shutting down server. Please be sure it is not running before hitting OK.\n\n" + e.Status + "\n\n" + e.Message);
  179. }
  180. }
  181. }
  182. else
  183. {
  184. if (!IsUpdate && PackageName == "MBTheater")
  185. {
  186. // Uninstalling MBT - shut it down if it is running
  187. var processes = Process.GetProcessesByName("mediabrowser.ui");
  188. if (processes.Length > 0)
  189. {
  190. lblStatus.Text = "Shutting Down Media Browser Theater...";
  191. try
  192. {
  193. processes[0].Kill();
  194. }
  195. catch (Exception ex)
  196. {
  197. MessageBox.Show("Unable to shutdown Media Browser Theater. Please ensure it is not running before hitting OK.\n\n" + ex.Message, "Error");
  198. }
  199. }
  200. }
  201. }
  202. // Download if we don't already have it
  203. if (archive == null)
  204. {
  205. lblStatus.Text = string.Format("Downloading {0} (version {1})...", FriendlyName, version.versionStr);
  206. try
  207. {
  208. archive = await DownloadPackage(version);
  209. }
  210. catch (Exception e)
  211. {
  212. SystemClose("Error Downloading Package - " + e.GetType().FullName + "\n\n" + e.Message);
  213. return;
  214. }
  215. }
  216. if (archive == null) return; //we canceled or had an error that was already reported
  217. if (Path.GetExtension(archive) == ".msi")
  218. {
  219. // Create directory for our installer log
  220. if (!Directory.Exists(RootPath)) Directory.CreateDirectory(RootPath);
  221. var logPath = Path.Combine(RootPath, "Logs");
  222. if (!Directory.Exists(logPath)) Directory.CreateDirectory(logPath);
  223. // Run in silent mode and wait for it to finish
  224. // First uninstall any previous version
  225. lblStatus.Text = "Uninstalling any previous version...";
  226. var logfile = Path.Combine(RootPath, "logs", "UnInstall.log");
  227. var uninstaller = Process.Start("msiexec", "/x \"" + archive + "\" /quiet /le \"" + logfile + "\"");
  228. if (uninstaller != null) uninstaller.WaitForExit();
  229. // And now installer
  230. lblStatus.Text = "Installing " + FriendlyName;
  231. logfile = Path.Combine(RootPath, "logs", "Install.log");
  232. var installer = Process.Start(archive, "/quiet /le \""+logfile+"\"");
  233. installer.WaitForExit(); // let this throw if there is a problem
  234. }
  235. else
  236. {
  237. // Extract
  238. lblStatus.Text = "Extracting Package...";
  239. try
  240. {
  241. ExtractPackage(archive);
  242. // We're done with it so delete it (this is necessary for update operations)
  243. TryDelete(archive);
  244. }
  245. catch (Exception e)
  246. {
  247. SystemClose("Error Extracting - " + e.GetType().FullName + "\n\n" + e.Message);
  248. // Delete archive even if failed so we don't try again with this one
  249. TryDelete(archive);
  250. return;
  251. }
  252. // Create shortcut
  253. lblStatus.Text = "Creating Shortcuts...";
  254. var fullPath = Path.Combine(RootPath, "System", TargetExe);
  255. try
  256. {
  257. CreateShortcuts(fullPath);
  258. }
  259. catch (Exception e)
  260. {
  261. SystemClose("Error Creating Shortcut - "+e.GetType().FullName+"\n\n"+e.Message);
  262. return;
  263. }
  264. // Install Pismo
  265. if (InstallPismo)
  266. {
  267. lblStatus.Text = "Installing ISO Support...";
  268. try
  269. {
  270. PismoInstall();
  271. }
  272. catch (Exception e)
  273. {
  274. SystemClose("Error Installing ISO support - "+e.GetType().FullName+"\n\n"+e.Message);
  275. }
  276. }
  277. // Now delete the pismo install files
  278. Directory.Delete(Path.Combine(RootPath, "Pismo"), true);
  279. }
  280. // And run
  281. lblStatus.Text = string.Format("Starting {0}...", FriendlyName);
  282. try
  283. {
  284. Process.Start(Path.Combine(EndInstallPath, TargetExe), TargetArgs);
  285. }
  286. catch (Exception e)
  287. {
  288. SystemClose("Error Executing - "+Path.Combine(EndInstallPath, TargetExe) + " " + TargetArgs + "\n\n" +e.GetType().FullName+"\n\n"+e.Message);
  289. return;
  290. }
  291. SystemClose();
  292. }
  293. private bool TryDelete(string file)
  294. {
  295. try
  296. {
  297. File.Delete(file);
  298. }
  299. catch (FileNotFoundException)
  300. {
  301. }
  302. catch (Exception e)
  303. {
  304. return false;
  305. }
  306. return true;
  307. }
  308. private void PismoInstall()
  309. {
  310. // Kick off the Pismo installer and wait for it to end
  311. var pismo = new Process();
  312. pismo.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  313. pismo.StartInfo.FileName = Path.Combine(RootPath, "Pismo", "pfminst.exe");
  314. pismo.StartInfo.Arguments = "install";
  315. pismo.Start();
  316. pismo.WaitForExit();
  317. }
  318. protected async Task<PackageVersionInfo> GetPackageVersion()
  319. {
  320. try
  321. {
  322. // get the package information for the server
  323. var json = await MainClient.DownloadStringTaskAsync("http://www.mb3admin.com/admin/service/package/retrieveAll?name=" + PackageName);
  324. var packages = JsonSerializer.DeserializeFromString<List<PackageInfo>>(json);
  325. var version = packages[0].versions.Where(v => v.classification <= PackageClass).OrderByDescending(v => v.version).FirstOrDefault(v => v.version <= RequestedVersion);
  326. if (version == null)
  327. {
  328. SystemClose("Could not locate download package. Aborting.");
  329. return null;
  330. }
  331. return version;
  332. }
  333. catch (Exception e)
  334. {
  335. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  336. }
  337. return null;
  338. }
  339. /// <summary>
  340. /// Download our specified package to an archive in a temp location
  341. /// </summary>
  342. /// <returns>The fully qualified name of the downloaded package</returns>
  343. protected async Task<string> DownloadPackage(PackageVersionInfo version)
  344. {
  345. var success = false;
  346. var retryCount = 0;
  347. var archiveFile = Path.Combine(PrepareTempLocation(), version.targetFilename);
  348. try
  349. {
  350. while (!success && retryCount < 3)
  351. {
  352. // setup download progress and download the package
  353. MainClient.DownloadProgressChanged += DownloadProgressChanged;
  354. try
  355. {
  356. await MainClient.DownloadFileTaskAsync(version.sourceUrl, archiveFile);
  357. success = true;
  358. }
  359. catch (WebException e)
  360. {
  361. if (e.Status == WebExceptionStatus.RequestCanceled)
  362. {
  363. return null;
  364. }
  365. if (retryCount < 3 && (e.Status == WebExceptionStatus.Timeout || e.Status == WebExceptionStatus.ConnectFailure || e.Status == WebExceptionStatus.ProtocolError))
  366. {
  367. Thread.Sleep(500); //wait just a sec
  368. PrepareTempLocation(); //clear this out
  369. retryCount++;
  370. }
  371. else
  372. {
  373. throw;
  374. }
  375. }
  376. }
  377. return archiveFile;
  378. }
  379. catch (Exception e)
  380. {
  381. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  382. }
  383. return "";
  384. }
  385. void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  386. {
  387. rectProgress.Width = (this.Width * e.ProgressPercentage)/100f;
  388. }
  389. /// <summary>
  390. /// Extract the provided archive to our program root
  391. /// It is assumed the archive is a zip file relative to that root (with all necessary sub-folders)
  392. /// </summary>
  393. /// <param name="archive"></param>
  394. protected void ExtractPackage(string archive)
  395. {
  396. // Delete old content of system
  397. var systemDir = Path.Combine(RootPath, "System");
  398. var backupDir = Path.Combine(RootPath, "System.old");
  399. if (Directory.Exists(systemDir))
  400. {
  401. try
  402. {
  403. if (Directory.Exists(backupDir)) Directory.Delete(backupDir,true);
  404. }
  405. catch (Exception e)
  406. {
  407. throw new ApplicationException("Could not delete previous backup directory.\n\n"+e.Message);
  408. }
  409. try
  410. {
  411. Directory.Move(systemDir, backupDir);
  412. }
  413. catch (Exception e)
  414. {
  415. throw new ApplicationException("Could not move system directory to backup.\n\n"+e.Message);
  416. }
  417. }
  418. // And extract
  419. var retryCount = 0;
  420. var success = false;
  421. while (!success && retryCount < 3)
  422. {
  423. try
  424. {
  425. using (var fileStream = File.OpenRead(archive))
  426. {
  427. using (var zipFile = ZipFile.Read(fileStream))
  428. {
  429. zipFile.ExtractAll(RootPath, ExtractExistingFileAction.OverwriteSilently);
  430. success = true;
  431. }
  432. }
  433. }
  434. catch (Exception e)
  435. {
  436. if (retryCount < 3)
  437. {
  438. Thread.Sleep(250);
  439. retryCount++;
  440. }
  441. else
  442. {
  443. //Rollback
  444. RollBack(systemDir, backupDir);
  445. TryDelete(archive); // so we don't try again if its an update
  446. throw new ApplicationException(string.Format("Could not extract {0} to {1} after {2} attempts.\n\n{3}", archive, RootPath, retryCount, e.Message));
  447. }
  448. }
  449. }
  450. }
  451. protected void RollBack(string systemDir, string backupDir)
  452. {
  453. if (Directory.Exists(backupDir))
  454. {
  455. if (Directory.Exists(systemDir)) Directory.Delete(systemDir);
  456. Directory.Move(backupDir, systemDir);
  457. }
  458. }
  459. /// <summary>
  460. /// Create a shortcut in the current user's start menu
  461. /// Only do current user to avoid need for admin elevation
  462. /// </summary>
  463. /// <param name="targetExe"></param>
  464. protected void CreateShortcuts(string targetExe)
  465. {
  466. // get path to all users start menu
  467. var startMenu = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),"Media Browser 3");
  468. if (!Directory.Exists(startMenu)) Directory.CreateDirectory(startMenu);
  469. var product = new ShellShortcut(Path.Combine(startMenu, FriendlyName+".lnk")) {Path = targetExe, Description = "Run " + FriendlyName};
  470. product.Save();
  471. if (PackageName == "MBServer")
  472. {
  473. var path = Path.Combine(startMenu, "MB Dashboard.lnk");
  474. var dashboard = new ShellShortcut(path)
  475. {Path = @"http://localhost:8096/mediabrowser/dashboard/dashboard.html", Description = "Open the Media Browser Server Dashboard (configuration)"};
  476. dashboard.Save();
  477. }
  478. CreateUninstaller(Path.Combine(Path.GetDirectoryName(targetExe) ?? "", "MediaBrowser.Uninstaller.exe")+ " "+ (PackageName == "MBServer" ? "server" : "mbt"), targetExe);
  479. }
  480. /// <summary>
  481. /// Create uninstall entry in add/remove
  482. /// </summary>
  483. /// <param name="uninstallPath"></param>
  484. /// <param name="targetExe"></param>
  485. private void CreateUninstaller(string uninstallPath, string targetExe)
  486. {
  487. var parent = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", true);
  488. {
  489. if (parent == null)
  490. {
  491. var rootParent = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion", true);
  492. {
  493. if (rootParent != null)
  494. {
  495. parent = rootParent.CreateSubKey("Uninstall");
  496. if (parent == null)
  497. {
  498. MessageBox.Show("Unable to create Uninstall registry key. Program is still installed sucessfully.");
  499. return;
  500. }
  501. }
  502. }
  503. }
  504. try
  505. {
  506. RegistryKey key = null;
  507. try
  508. {
  509. const string guidText = "{4E76DB4E-1BB9-4A7B-860C-7940779CF7A0}";
  510. key = parent.OpenSubKey(guidText, true) ??
  511. parent.CreateSubKey(guidText);
  512. if (key == null)
  513. {
  514. MessageBox.Show(String.Format("Unable to create uninstaller entry'{0}\\{1}'. Program is still installed successfully.", @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", guidText));
  515. return;
  516. }
  517. key.SetValue("DisplayName", FriendlyName);
  518. key.SetValue("ApplicationVersion", ActualVersion);
  519. key.SetValue("Publisher", "Media Browser Team");
  520. key.SetValue("DisplayIcon", targetExe);
  521. key.SetValue("DisplayVersion", ActualVersion.ToString(2));
  522. key.SetValue("URLInfoAbout", "http://www.mediabrowser3.com");
  523. key.SetValue("Contact", "http://community.mediabrowser.tv");
  524. key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd"));
  525. key.SetValue("UninstallString", uninstallPath);
  526. }
  527. finally
  528. {
  529. if (key != null)
  530. {
  531. key.Close();
  532. }
  533. }
  534. }
  535. catch (Exception ex)
  536. {
  537. MessageBox.Show("An error occurred writing uninstall information to the registry.");
  538. }
  539. }
  540. }
  541. /// <summary>
  542. /// Prepare a temporary location to download to
  543. /// </summary>
  544. /// <returns>The path to the temporary location</returns>
  545. protected string PrepareTempLocation()
  546. {
  547. ClearTempLocation(TempLocation);
  548. Directory.CreateDirectory(TempLocation);
  549. return TempLocation;
  550. }
  551. /// <summary>
  552. /// Clear out (delete recursively) the supplied temp location
  553. /// </summary>
  554. /// <param name="location"></param>
  555. protected void ClearTempLocation(string location)
  556. {
  557. if (Directory.Exists(location))
  558. {
  559. Directory.Delete(location, true);
  560. }
  561. }
  562. }
  563. }