MainWindow.xaml.cs 20 KB

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