MainWindow.xaml.cs 20 KB

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