MainWindow.xaml.cs 19 KB

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