MainWindow.xaml.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. try
  244. {
  245. File.Delete(archive);
  246. }
  247. catch (FileNotFoundException)
  248. {
  249. }
  250. catch (Exception e)
  251. {
  252. SystemClose("Error Removing Archive - " + e.GetType().FullName + "\n\n" + e.Message);
  253. return;
  254. }
  255. }
  256. catch (Exception e)
  257. {
  258. SystemClose("Error Extracting - " + e.GetType().FullName + "\n\n" + e.Message);
  259. return;
  260. }
  261. // Create shortcut
  262. lblStatus.Text = "Creating Shortcuts...";
  263. var fullPath = Path.Combine(RootPath, "System", TargetExe);
  264. try
  265. {
  266. CreateShortcuts(fullPath);
  267. }
  268. catch (Exception e)
  269. {
  270. SystemClose("Error Creating Shortcut - "+e.GetType().FullName+"\n\n"+e.Message);
  271. return;
  272. }
  273. // Install Pismo
  274. if (InstallPismo)
  275. {
  276. lblStatus.Text = "Installing ISO Support...";
  277. try
  278. {
  279. PismoInstall();
  280. }
  281. catch (Exception e)
  282. {
  283. SystemClose("Error Installing ISO support - "+e.GetType().FullName+"\n\n"+e.Message);
  284. }
  285. }
  286. // Now delete the pismo install files
  287. Directory.Delete(Path.Combine(RootPath, "Pismo"), true);
  288. }
  289. // And run
  290. lblStatus.Text = string.Format("Starting {0}...", FriendlyName);
  291. try
  292. {
  293. Process.Start(Path.Combine(EndInstallPath, TargetExe), TargetArgs);
  294. }
  295. catch (Exception e)
  296. {
  297. SystemClose("Error Executing - "+Path.Combine(EndInstallPath, TargetExe) + " " + TargetArgs + "\n\n" +e.GetType().FullName+"\n\n"+e.Message);
  298. return;
  299. }
  300. SystemClose();
  301. }
  302. private void PismoInstall()
  303. {
  304. // Kick off the Pismo installer and wait for it to end
  305. var pismo = new Process();
  306. pismo.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  307. pismo.StartInfo.FileName = Path.Combine(RootPath, "Pismo", "pfminst.exe");
  308. pismo.StartInfo.Arguments = "install";
  309. pismo.Start();
  310. pismo.WaitForExit();
  311. }
  312. protected async Task<PackageVersionInfo> GetPackageVersion()
  313. {
  314. try
  315. {
  316. // get the package information for the server
  317. var json = await MainClient.DownloadStringTaskAsync("http://www.mb3admin.com/admin/service/package/retrieveAll?name=" + PackageName);
  318. var packages = JsonSerializer.DeserializeFromString<List<PackageInfo>>(json);
  319. var version = packages[0].versions.Where(v => v.classification <= PackageClass).OrderByDescending(v => v.version).FirstOrDefault(v => v.version <= RequestedVersion);
  320. if (version == null)
  321. {
  322. SystemClose("Could not locate download package. Aborting.");
  323. return null;
  324. }
  325. return version;
  326. }
  327. catch (Exception e)
  328. {
  329. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  330. }
  331. return null;
  332. }
  333. /// <summary>
  334. /// Download our specified package to an archive in a temp location
  335. /// </summary>
  336. /// <returns>The fully qualified name of the downloaded package</returns>
  337. protected async Task<string> DownloadPackage(PackageVersionInfo version)
  338. {
  339. var success = false;
  340. var retryCount = 0;
  341. var archiveFile = Path.Combine(PrepareTempLocation(), version.targetFilename);
  342. try
  343. {
  344. while (!success && retryCount < 3)
  345. {
  346. // setup download progress and download the package
  347. MainClient.DownloadProgressChanged += DownloadProgressChanged;
  348. try
  349. {
  350. await MainClient.DownloadFileTaskAsync(version.sourceUrl, archiveFile);
  351. success = true;
  352. }
  353. catch (WebException e)
  354. {
  355. if (e.Status == WebExceptionStatus.RequestCanceled)
  356. {
  357. return null;
  358. }
  359. if (retryCount < 3 && (e.Status == WebExceptionStatus.Timeout || e.Status == WebExceptionStatus.ConnectFailure || e.Status == WebExceptionStatus.ProtocolError))
  360. {
  361. Thread.Sleep(500); //wait just a sec
  362. PrepareTempLocation(); //clear this out
  363. retryCount++;
  364. }
  365. else
  366. {
  367. throw;
  368. }
  369. }
  370. }
  371. return archiveFile;
  372. }
  373. catch (Exception e)
  374. {
  375. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  376. }
  377. return "";
  378. }
  379. void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  380. {
  381. rectProgress.Width = (this.Width * e.ProgressPercentage)/100f;
  382. }
  383. /// <summary>
  384. /// Extract the provided archive to our program root
  385. /// It is assumed the archive is a zip file relative to that root (with all necessary sub-folders)
  386. /// </summary>
  387. /// <param name="archive"></param>
  388. protected void ExtractPackage(string archive)
  389. {
  390. // Delete old content of system
  391. var systemDir = Path.Combine(RootPath, "System");
  392. var backupDir = Path.Combine(RootPath, "System.old");
  393. if (Directory.Exists(systemDir))
  394. {
  395. if (Directory.Exists(backupDir)) Directory.Delete(backupDir,true);
  396. Directory.Move(systemDir, backupDir);
  397. }
  398. // And extract
  399. var retryCount = 0;
  400. var success = false;
  401. while (!success && retryCount < 3)
  402. {
  403. try
  404. {
  405. using (var fileStream = File.OpenRead(archive))
  406. {
  407. using (var zipFile = ZipFile.Read(fileStream))
  408. {
  409. zipFile.ExtractAll(RootPath, ExtractExistingFileAction.OverwriteSilently);
  410. success = true;
  411. }
  412. }
  413. }
  414. catch
  415. {
  416. if (retryCount < 3)
  417. {
  418. Thread.Sleep(250);
  419. retryCount++;
  420. }
  421. else
  422. {
  423. //Rollback
  424. RollBack(systemDir, backupDir);
  425. File.Delete(archive); // so we don't try again if its an update
  426. throw;
  427. }
  428. }
  429. }
  430. }
  431. protected void RollBack(string systemDir, string backupDir)
  432. {
  433. if (Directory.Exists(backupDir))
  434. {
  435. if (Directory.Exists(systemDir)) Directory.Delete(systemDir);
  436. Directory.Move(backupDir, systemDir);
  437. }
  438. }
  439. /// <summary>
  440. /// Create a shortcut in the current user's start menu
  441. /// Only do current user to avoid need for admin elevation
  442. /// </summary>
  443. /// <param name="targetExe"></param>
  444. protected void CreateShortcuts(string targetExe)
  445. {
  446. // get path to all users start menu
  447. var startMenu = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),"Media Browser 3");
  448. if (!Directory.Exists(startMenu)) Directory.CreateDirectory(startMenu);
  449. var product = new ShellShortcut(Path.Combine(startMenu, FriendlyName+".lnk")) {Path = targetExe, Description = "Run " + FriendlyName};
  450. product.Save();
  451. if (PackageName == "MBServer")
  452. {
  453. var path = Path.Combine(startMenu, "MB Dashboard.lnk");
  454. var dashboard = new ShellShortcut(path)
  455. {Path = @"http://localhost:8096/mediabrowser/dashboard/dashboard.html", Description = "Open the Media Browser Server Dashboard (configuration)"};
  456. dashboard.Save();
  457. }
  458. CreateUninstaller(Path.Combine(Path.GetDirectoryName(targetExe) ?? "", "MediaBrowser.Uninstaller.exe")+ " "+ (PackageName == "MBServer" ? "server" : "mbt"), targetExe);
  459. }
  460. /// <summary>
  461. /// Create uninstall entry in add/remove
  462. /// </summary>
  463. /// <param name="uninstallPath"></param>
  464. /// <param name="targetExe"></param>
  465. private void CreateUninstaller(string uninstallPath, string targetExe)
  466. {
  467. var parent = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", true);
  468. {
  469. if (parent == null)
  470. {
  471. var rootParent = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion", true);
  472. {
  473. if (rootParent != null)
  474. {
  475. parent = rootParent.CreateSubKey("Uninstall");
  476. if (parent == null)
  477. {
  478. MessageBox.Show("Unable to create Uninstall registry key. Program is still installed sucessfully.");
  479. return;
  480. }
  481. }
  482. }
  483. }
  484. try
  485. {
  486. RegistryKey key = null;
  487. try
  488. {
  489. const string guidText = "{4E76DB4E-1BB9-4A7B-860C-7940779CF7A0}";
  490. key = parent.OpenSubKey(guidText, true) ??
  491. parent.CreateSubKey(guidText);
  492. if (key == null)
  493. {
  494. MessageBox.Show(String.Format("Unable to create uninstaller entry'{0}\\{1}'. Program is still installed successfully.", @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", guidText));
  495. return;
  496. }
  497. key.SetValue("DisplayName", FriendlyName);
  498. key.SetValue("ApplicationVersion", ActualVersion);
  499. key.SetValue("Publisher", "Media Browser Team");
  500. key.SetValue("DisplayIcon", targetExe);
  501. key.SetValue("DisplayVersion", ActualVersion.ToString(2));
  502. key.SetValue("URLInfoAbout", "http://www.mediabrowser3.com");
  503. key.SetValue("Contact", "http://community.mediabrowser.tv");
  504. key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd"));
  505. key.SetValue("UninstallString", uninstallPath);
  506. }
  507. finally
  508. {
  509. if (key != null)
  510. {
  511. key.Close();
  512. }
  513. }
  514. }
  515. catch (Exception ex)
  516. {
  517. MessageBox.Show("An error occurred writing uninstall information to the registry.");
  518. }
  519. }
  520. }
  521. /// <summary>
  522. /// Prepare a temporary location to download to
  523. /// </summary>
  524. /// <returns>The path to the temporary location</returns>
  525. protected string PrepareTempLocation()
  526. {
  527. ClearTempLocation(TempLocation);
  528. Directory.CreateDirectory(TempLocation);
  529. return TempLocation;
  530. }
  531. /// <summary>
  532. /// Clear out (delete recursively) the supplied temp location
  533. /// </summary>
  534. /// <param name="location"></param>
  535. protected void ClearTempLocation(string location)
  536. {
  537. if (Directory.Exists(location))
  538. {
  539. Directory.Delete(location, true);
  540. }
  541. }
  542. }
  543. }