MainWindow.xaml.cs 20 KB

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