MainWindow.xaml.cs 22 KB

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